PHP DomDocument editing all links

2019-04-09 20:06发布

问题:

I am using the following code to grab html from another page and place it into my php page:

$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);

I want to change all instances of <a href="/somepath/file.htm"> so that I can prepend to it the actual domain instead. How can I do this?

So, it would need to change them to: <a href="http://mydomain.com/somepath/file.htm"> instead.

回答1:

try something like:

$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();