I am trying to run a simple PHP SimpleXML command using xpath. But, my //w:pStyle
Xpath is getting all nodes in the entire document and not the ones relative to the node //w:p
thats being looped. Note: I want to keep the loop for both xpaths separate. I do not want to have both under one xpath i.e. loop through the paragraph nodes and then loop the styles nodes only in that paragraph if they exist.
foreach($file->xpath('//w:p') as $p){
echo 'Paragraph';
$styles=$p->xpath('//w:pStyle');
foreach($styles as $style){echo 'Style';}
}
The xpath //w:pStyle
selects all the w:pStyle
nodes. I would like instead for it to select the ones that are relative to the paragraph node. What is the solution here?
Your mistake is, that you are selecting elements from the whole document by prefixing the expression with //
. You should prefix it with .//
instead, like this
$styles=$p->xpath('.//w:pStyle');
which will select all w:pStyle
descendants of the w:p
element.
If you only want direct children of w:p
, use
$styles=$p->xpath('w:pStyle');
since w:pStyle
is a child of w:pPr
which is a child of w:p
, you could use
$styles=$p->xpath('w:pPr/w:pStyle');