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 (ie some-text
) or a part of it (ie 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?
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.