我很难理解如何在PHP中使用DOMElement对象。我找到了这段代码,但是我不确定它是否适用于我:
$dom = new DOMDocument();
$dom->loadHTML("index.php");
$div = $dom->getElementsByTagName('div');
foreach ($div->attributes as $attr) {
$name = $attr->nodeName;
$value = $attr->nodeValue;
echo "Attribute '$name' :: '$value'
";
}
基本上,我需要在DOM中搜索element特定的id,之后需要提取一个非标准的attribute(即我用JS编写并使用的非标准的),以便可以看到它的价值。原因是我需要从中获取$_GET一份,而在HTML中则需要基于重定向。如果有人可以解释一下我如何为此目的使用DOMDocument,那将有所帮助。我真的很难理解发生了什么以及如何正确实施它,因为我显然做得不好。
编辑(我根据评论所在):
这是我的代码行4-26供参考:
require_once($_SERVER["DOCUMENT_ROOT"] . "/peripheral/profile.php");
$searchResults = isset($_GET["s"]) ? performSearch($_GET["s"]) : "";
$dom = new DOMDocument();
$dom->load("index.php");
$divs = $dom->getElementsByTagName('div');
foreach ($divs as $div) {
foreach ($div->attributes as $attr) {
$name = $attr->nodeName;
$value = $attr->nodeValue;
echo "Attribute '$name' :: '$value'
";
}
}
$div = $dom->getElementById('currentLocation');
$attr = $div->getAttribute('srckey');
echo "
{$attr}";
?>
这是我收到的错误消息:
Warning: DOMDocument::load() [domdocument.load]: Extra content at the end of the document in ../public_html/index.php, line: 26 in ../public_html/index.php on line 10
Fatal error: Call to a member function getAttribute() on a non-object in ../public_html/index.php on line 21