2013-03-18 52 views
3

我使用下面的代码从另一个页面抓取HTML,并把它变成我的PHP页面:PHP的DomDocument编辑各个环节

$doc = new DomDocument; 

// We need to validate our document before refering to the id 
$doc->validateOnParse = true; 
$doc->loadHtml(file_get_contents('{URL IS HERE}')); 
$content = $doc->getElementById('form2'); 

echo $doc->SaveHTML($content); 

我想改变的<a href="/somepath/file.htm">所有实例,这样我可以预先考虑到它实际的域名。我怎样才能做到这一点?

因此,它需要将它们改为:<a href="http://mydomain.com/somepath/file.htm">

+0

如果我是你,我会尽量避免使用'DomDocument'并直接使用正则表达式来找出链接和编辑。 – Raptor 2013-03-18 03:23:38

+3

怎么回事?无处不在我堆栈溢出,他们说你应该使用'DomDocument'。你能给我一个如何用正则表达式来做这个例子吗? – 2013-03-18 03:25:33

+0

您可以为查找和替换任务创建额外的对象。额外解析时间和内存花费。尝试:http://stackoverflow.com/questions/4001328/php-regex-to-get-string-inside-href-tag – Raptor 2013-03-18 03:29:14

回答

3

尝试类似:

$xml = new DOMDocument(); 
$xml->loadHTMLFile($url); 
foreach($xml->getElementsByTagName('a') as $link) { 
    $oldLink = $link->getAttribute("href"); 
    $link->setAttribute('href', "http://mydomain.com/" . $oldLink); 
} 
echo $xml->saveHtml(); 
+0

但是'href'是每个链接都不同,所以我只需要预先定义域到它。它只是:'$ link-> setAttribute('href',“http://mydomain.com/”+ $ link-> getAttribute('href'));'? – 2013-03-18 03:36:07

+0

@SolomonClosson是的,检查我更新的答案 – 2013-03-18 03:44:33

+0

好的,太好了,但我得到'$ content'不是整个文档。无论如何,我从你的答案中找出答案。所以,你明白了。谢谢:) – 2013-03-18 03:47:49