1

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?

1 Answer 1

3

Yes, you can use a query like //url/loc[contains(., "other-text")]


Example:

$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);
}

Output:

<loc>some-other-text</loc>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.