DOMDocument getelementbyid conflict?


DOMDocument getelementbyid conflict?

我有一个javascript弹出窗口,它"成功"地使用php将另一个页面加载为DOMDocument,并"成功"通过id找到一个元素,以使用nodeValue显示其文本。。。但是。。。nodeValue调用返回的不是所需元素内的文本,而是具有相同名称的锚点标记内的文本。以下是一些代码:

看似"有效"的html和php:

<span style="position:relative;"><span id="favelas" class="popup">
<?php
// Create a new DOMDocument object
$doc = new DOMDocument;
// enable user error handling
libxml_use_internal_errors(true);
// Validate our document before referring to the id
$doc->validateOnParse = true;
// Load the key terms and identifications html file
$doc->loadHtml(file_get_contents('http://teachers.dadeschools.net/jzoeller/APHG/0-Key-Terms-Identifications.html'));
// Print in readable form the content the element by id
print_r($doc->getElementById('favela')->nodeValue);
?>
</span><a href="javascript:void(null);" onMouseover="ShowPop('favelas');" onMouseout="HidePop('favelas');">favelas</a></span>

现在,"应该"显示的是上面代码中引用的页面中贫民窟一词的定义。我得到的只是"贫民窟"这个词。

以下是更多的代码,这次来自php:加载的页面

<tr>
<td><a name="favela">
favela</a></td>
<td class="def" id="favela">A shantytown or slum, especially in Brazil.</td>
<td>07</td>
<td>06</td>
</tr>

使用var_dump进行调试会得到以下结果:

object(DOMElement)#1(17){["tagName"]=>string(1)"a"["schemaTypeInfo"]=>NULL["nodeName"]=>string(1 string(22)"(省略对象值)">["previousSibling"]=>NULL["attributes"]=>字符串(22)"(省略对象值)">["ownerDocument"]=>string(22)"(省略对象数值)"["namespaceURI"]=>NULL>["prefix"]=>string(0)"["localName"]=>string(1)"a"["baseURI"]=>NULL>["textContent"]=>string(8)"favela"}

这似乎是在说,它得到了名为"贫民窟"的主播,而不是名为"贫民区"的td。什么?!

您可以使用DOMXPath查询而不是getElementById()来避开name属性,并仅针对id属性为"favela"的元素:

$xpath = new DOMXPath($doc);
$favelaElement = $xpath->query('//*[@id="favela"]')->item(0);
print_r($favelaElement->nodeValue);

输出:

A shantytown or slum, especially in Brazil.