Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php基于getAttribute从html中删除标记_Php - Fatal编程技术网

php基于getAttribute从html中删除标记

php基于getAttribute从html中删除标记,php,Php,如何通过指定$tag->getAttribute('rel')=“icon”来限制删除哪个链接标记?我尝试将一个简单的if语句添加到$remove[]$tags作为$tag行…代码已运行,但带有rel=“icon”行的链接根本没有删除 因此,在本例中,应从html中删除整个链接标记: <link rel="icon" type="image/png" href="/images/favicon.ico" /> $html = file_get_contents($url); $d

如何通过指定
$tag->getAttribute('rel')=“icon”
来限制删除哪个链接标记?我尝试将一个简单的if语句添加到
$remove[]$tags作为$tag行…代码已运行,但带有
rel=“icon”
行的链接根本没有删除

因此,在本例中,应从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); 
}
通过添加以下行作为代码的最后一行…工作非常完美

$html = $dom->saveHTML();

您可以通过xpath获得所有这些:

$html = file_get_contents($url);
$dom = new DOMDocument();
$dom->loadHTML($html);
$finder = new DOMXpath($dom);
$tags = $finder->query('//link[@rel="icon"]');
$toRemove = array();

foreach ($tags as $tag)
{
  $toRemove[] = $tag;
}

// with array walk
array_walk(function($elem) { $elem->parentNode->removeChild($elem); }, $toRemove);

// with foreach
foreach ($toRemove as $tag) {
  $tag->parentNode->removeChild($tag);
}

您可以使用函数str_replace的简易方法:

<?php

//$html = file_get_contents($url);

$html = '<a rel="icon" href="#">link</a>';
$html = str_replace('rel="icon"', 'rel=""', $html);

echo $html;
?>

为什么不使用str_replace?如果rel=“icon”,我不知道str_replace如何删除整个链接标签。因此,如果链接rel=“icon”完全删除此项。我试过你的例子……代码运行完毕,但链接仍然存在。@KurtMarshman显然,当你在DOMNodeList上迭代时,你无法进行就地删除-出于某种原因,你需要将元素踢到数组中。答案已更新。(注意:我没有试过这段代码,但我是这样评论的:)@prodigitalson…你第一次是对的。只少了一行。非常感谢你。
<?php

//$html = file_get_contents($url);

$html = '<a rel="icon" href="#">link</a>';
$html = str_replace('rel="icon"', 'rel=""', $html);

echo $html;
?>