【发布时间】:2015-06-09 01:01:27
【问题描述】:
我有一个 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>
现在,“应该”显示的是上面代码中引用的页面中 favela 一词的定义。我得到的只是“贫民窟”这个词。
这里还有一些代码,这次来自 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) "a" ["nodeValue"]=> string(8) "favela" >["nodeType"]=> int(1) ["parentNode"]=> string(22) "(省略对象值)" >["childNodes"] => string(22) "(省略对象值)" ["firstChild"]=> string(22) >"(省略对象值)" ["lastChild"]=> string(22) "(省略对象值)" >["previousSibling"]=> NULL ["attributes"]=> string(22) "(省略对象值)" >["ownerDocument"]=> string(22) "(省略对象值)" ["namespaceURI" ]=> NULL >["prefix"]=> string(0) "" ["localName"]=> string(1) "a" ["baseURI"]=> NULL >["textContent"]=> string( 8)“贫民窟”}
这似乎是说它得到了名为“favela”的锚,而不是名为“favela”的 td。什么给了?!
【问题讨论】:
-
为什么这被标记为“Javascript”。这不是一个关于 PHP 实现的 DOMDocument 的 PHP 问题吗?
-
我不太了解 DOMDocument,但我认为它将 html 作为 html40 松散 处理,并且
a元素的name属性是 ID 属性(ID 属性不需要名称为id)。至此,您将找到a。 -
好的,所以,正如我所怀疑的,它在锚上绊倒了;那么如何跳过锚点并获取 id 的第二个实例,在本例中为“favela”。另外,感谢您的解释。我希望我的解决方案同样简洁!
-
使用 DOMXPath 搜索
//[@id='favela']可能会成功,但正如我所说,我不太了解DOMDocument,所以我不知道我的假设是否真的正确,也不知道 @987654329 是否正确@ 会遇到同样的问题。
标签: javascript php html