我正在尝试访问使用preg_match找到的元素的parentNode,因为我想通过文档的DOM读取通过regex找到的结果。我无法通过PHP的DOMDocument直接访问它,因为div的数量是可变的,并且它们没有实际ID或任何其他能够匹配的属性。
为了说明这一点:在下面的示例中,我将match_me
与preg_match匹配,然后我想访问parentNode(div)并将所有子元素(p)放在DOMdocument对象中,所以我可以很容易地显示它们。
<div>
.... variable amount of divs
<div>
<div>
<p>1 match_me</p><p>2</p>
</div>
</div>
</div>
答案 0 :(得分:1)
使用DOMXpath
按子节点的值查询节点:
$dom = new DOMDocument();
// Load your doc however necessary...
$xpath = new DOMXpath($dom);
// This query should match the parent div itself
$nodes = $xpath->query('/div[p/text() = "1 match_me"]');
$your_div = $nodes->item(0);
// Do something with the children
$p_tags = $your_div->childNodes;
// Or in this version, the query returns the `<p>` on which `parentNode` is called
$ndoes = $xpath->query('/p[text() = "1 match_me"]');
$your_div = $nodes->item(0)->parentNode;