PHP DOMDocument GetElementsByTagName Not Finding Elements

半世苍凉 提交于 2019-12-06 16:12:58

Are you sure the tags aren't being matched? What is the output of var_dump? What value do you get when you use var_dump($metaChildren->length)? Your code seems to work here:

<?
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->loadHtmlFile('test.html');
$metaChildren = $dom->getElementsByTagName('meta');
for ($i = 0; $i < $metaChildren->length; $i++) {
  $el = $metaChildren->item($i);
  print $el->getAttribute('name') . '=' . $el->getAttribute('content') . "\n";
}
?>

Gives output:

GZPlatform= pc
GZFeatured= Gone Gold
GZHeadline= pc
GZP_ID= pc 21153

My guess would be that the HTML is not valid and that the $dom->loadHtml call is failing. I believe that call returns true|false. So maybe something like this:

if($dom->loadHtml($contents)){
    $metaChildren = $dom->getElementsByTagName('meta');
}else{
    //handle properly
}

COuld it be that the parser expects you to close the meta tags?

<meta name="name" />

or

<meta name="name"></meta>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!