LostInTheCode
LostInTheCode

Reputation: 1744

PHP DOMDocument's getElementsByTagName()

I have an XML file shown below:

<?xml version="1.0" encoding="UTF-8"?>
<xml>
    <job>
        <id>4200021</id>
        <sector>Downtown</sector>
        <title>Clean Windows</title>
    </job>

    <job>
        <id>2100021</id>
        <sector>Downtown</sector>
        <title>Fix Manholes</title>
    </job>
</xml>

I'm using PHP's DOMDocument, and I'm trying to get the <id> of the job by searching the title.

I use this to get the <job> node in question:

$job = $jobDoc->getElementsByTagName('Clean Windows')->item(0)->parentNode;

However, I have iterate through all the nodes by calling nodeName for each node to get the correct ID, is there another simpler way to find the correct id using DOMDocument? I can't call getElementsByTagName() again on the parentNode, and doing this manually becomes a problem when I have to search once again, within another node to find the in the node , which is part of the nodes.

Upvotes: 0

Views: 388

Answers (1)

Wrikken
Wrikken

Reputation: 70460

$doc = new DOMDocument();
$doc->loadXML($your_xml);
$x = new DOMXPath($doc);
$id = $x->query("//title[. = 'Clean Windows']/../id/text()")->item(0)->wholeText;

Upvotes: 2

Related Questions