How can I limit which link tag is removed by specifying $tag->getAttribute('rel') = "icon"
? I tried adding a simple if statement to the $remove[] $tags as $tag;
line...code ran through, but the link with rel="icon"
line was not at all removed.
So in this example the whole link tag should be removed from the html:
<link rel="icon" type="image/png" href="/images/favicon.ico" />
$html = file_get_contents($url);
$dom = new DOMDocument();
$dom->loadHTML($html);
$tags = $dom->getElementsByTagName('link');
$remove = [];
foreach($tags as $tag) {
$remove[] = $tag;
}
foreach ($remove as $tag) {
$tag->parentNode->removeChild($tag);
}
UPDATE Answer here: @prodigitalson provided the following which initially did not work:
$html = file_get_contents($url);
$dom = new DOMDocument();
$dom->loadHTML($html);
$finder = new DOMXpath($dom);
$tags = $finder->query('//link[@rel="icon"]');
foreach ($tags as $tag)
{
$tag->parentNode->removeChild($tag);
}
by adding the following line as the last line of the code...worked perfect.
$html = $dom->saveHTML();