Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
852 views
in Technique[技术] by (71.8m points)

xml - Access an element's parent with PHP's SimpleXML?

I'm iterating through a set of SimpleXML objects, and I can't figure out how to access each object's parent node. Here's what I want:

$divs = simplexml->xpath("//div");
foreach ($divs as $div)
{
   $parent_div = $div->get_parent_node(); // Sadly, there's no such function.
}

Seems like there must be a fairly easy way to do this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could run a simple XPath query to get it:

$parent_div = $div->xpath("parent::*");

And as this is Simplexml and it only has element and attribute nodes and a parent node can only be an element and never an attribute, the abbreviated syntax can be used:

$parent_div = $div->xpath("..");

(via: Common Xpath Cheats - SimpleXML Type Cheatsheet (Feb 2013; by hakre) )


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...