Reputation: 1970
I have the following XML structure
<url>
<loc>some-text</loc>
</url>
<url>
<loc>some-other-text</loc>
</url>
My goal is to get loc
node from it's inner text (i.e. some-text
) or a part of it (i.e. other-text
). Here's my best attempt:
$doc = new DOMDocument('1.0','UTF-8');
$doc->load($filename);
$xpath = new Domxpath($doc);
$locs = $xpath->query('/url/loc');
foreach($locs as $loc) {
if(preg_match("/other-text/i", $loc->nodeValue)) return $loc->parentNode;
}
Is it possible to get specific loc
node without iterating over all nodes, simply using xpath query?
Upvotes: 1
Views: 1029
Reputation: 26375
Yes, you can use a query like //url/loc[contains(., "other-text")]
$xml = <<<'XML'
<root>
<url>
<loc>some-text</loc>
</url>
<url>
<loc>some-other-text</loc>
</url>
</root>
XML;
$dom = new DOMDocument();
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//url/loc[contains(., "other-text")]') as $node) {
echo $dom->saveXML($node);
}
<loc>some-other-text</loc>
Upvotes: 3