DOMElement getElementsByTagName()不起作用

时间:2014-10-13 04:39:31

标签: php html domdocument

当我在此代码中回显结果时,为什么我没有得到任何东西:

$result1 = '<HTML><HEAD><TITLE>Moved Temporarily</TITLE></HEAD><BODY BGCOLOR="#FFFFFF" TEXT="#000000"><H1>Moved Temporarily</H1>The document has moved <A HREF="https://accounts.google.com/ServiceLogin?service=lso&amp;">here</A>.</BODY></HTML>';
$dom = new DOMDocument;
$dom->loadHTML($result1);
$items = $dom->getElementsByTagName('HEAD');
echo $items->item(0); // error

1 个答案:

答案 0 :(得分:3)

您必须使用小写标记名称:

$result1 = '<HTML><HEAD><TITLE>Moved Temporarily</TITLE></HEAD><BODY BGCOLOR="#FFFFFF" TEXT="#000000"><H1>Moved Temporarily</H1>The document has moved <A HREF="https://accounts.google.com/ServiceLogin?service=lso&amp;">here</A>.</BODY></HTML>';
$dom = new DOMDocument;
$dom->loadHTML($result1);
$items = $dom->getElementsByTagName('head');
                                     ^^^

旁注:始终打开错误报告以获取有用信息:

error_reporting(E_ALL);
ini_set('display_errors', '1');

你不能直接回应,因为这会返回DOM类。

循环过头儿童:

echo '<pre>';
foreach($items->item(0)->childNodes as $child) {
    print_r($child); // most likely this will show you the child `<title>` node
}