使用PHP获取DOM元素

我很难理解如何在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'<br />";

}

基本上,我需要在DOM中搜索element特定的id,之后需要提取一个非标准的attribute(即我用JS编写并使用的非标准的),以便可以看到它的价值。原因是我需要从中获取$_GET一份,而在HTML中则需要基于重定向。如果有人可以解释一下我如何为此目的使用DOMDocument,那将有所帮助。我真的很难理解发生了什么以及如何正确实施它,因为我显然做得不好。

这是我的代码行4-26供参考:

<div id="column_profile">

<?php

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'<br />";

}

}

$div = $dom->getElementById('currentLocation');

$attr = $div->getAttribute('srckey');

echo "<h1>{$attr}</a>";

?>

</div>

<div id="column_main">

这是我收到的错误消息:

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

回答:

getElementsByTagName 返回一个元素列表,因此首先需要遍历这些元素,然后遍历它们的属性。

$divs = $dom->getElementsByTagName('div');

foreach ($divs as $div) {

foreach ($div->attributes as $attr) {

$name = $attr->nodeName;

$value = $attr->nodeValue;

echo "Attribute '$name' :: '$value'<br />";

}

}

对于您的情况,您说您需要一个特定的ID。这些应该是唯一的,因此可以使用它(注意,getElementById除非$dom->validate()先调用,否则可能不起作用):

$div = $dom->getElementById('divID');

然后获取您的属性:

$attr = $div->getAttribute('customAttr');

$dom->loadHTML只是读取文件的内容,它不执行它们。 index.php不会以这种方式运行。您可能需要执行以下操作:

$dom->loadHTML(file_get_contents('http://localhost/index.php'))

以上是 使用PHP获取DOM元素 的全部内容, 来源链接: utcz.com/qa/429256.html

回到顶部