xml - PHP DOM Document - get everything between two nodes -
i have part of xml loading in dom document:
<error n='\author'/> text 1 <formula type='inline'><math xmlns='http://www.w3.org/1998/math/mathml'><msup><mrow/> <mrow><mn>1</mn><mo>,</mo></mrow> </msup></math></formula> text 2 <formula type='inline'><math xmlns='http://www.w3.org/1998/math/mathml'><msup><mrow/> <mn>2</mn> </msup></math></formula> <error n='\address' />
my goal nodevalue between
<error n='\author' />
and
<error n='\address' />
how can done?
i tested this:
$author_node = $xpath_xml->query("//error[@n='\author']/following-sibling::*[1]")->item(0); if ($author_node != null) { $i = 1; $nextnodename = ""; $author = ""; while ($nextnodename != "error" && $i < 20) { $nextnodename = $xpath_xml->query("//error[@n='\author']/following-sibling::*[$i]")->item(0)->tagname; if ($nextnodename == "error") continue; $author .= $nextnode->nodevalue; }
but getting formula content, not text between formulas. thank you.
the *
only selects element nodes, not text nodes. <formula>
elements selected. need use node()
. use xpath directly selected needed nodes. explanation of kayessian method.
$dom = new domdocument(); $dom->loadxml($xml); $xpath = new domxpath($dom); $nodes = $xpath->evaluate( '//error[@n="\\author"][1] /following-sibling::node() [ count( .| //error[@n="\\author"][1] /following-sibling::error[@n="\\address"][1] /preceding-sibling::node() ) = count( //error[@n="\\author"][1] /following-sibling::error[@n="\\address"][1] /preceding-sibling::node() ) ]' ); $result = ''; foreach ($nodes $node) { $result .= $node->nodevalue; } var_dump($result);
demo: https://eval.in/125494
if want save not text content, xml fragment, can use domdocument::savexml() node argument.
$result = ''; foreach ($nodes $node) { $result .= $node->ownerdocument->savexml($node); } var_dump($result);
Comments
Post a Comment