r0tterz
r0tterz

Reputation: 308

Get XML element by ID with PHP

I'm having some difficulties getting PHP to read my XML document. I'm trying to echo the content from each node based on whatever catid I've selected.

XML: text.xml

<root>
  <category catid='1'>
    <text id='TXT1'><![CDATA[ Lorem Ipsum ]]></text>
    <text id='TXT2'><![CDATA[ Lorem Ipsum ]]></text>
    <text id='TXT3'><![CDATA[ Lorem Ipsum ]]></text>
  </category>
  <category catid='2'>
    <text id='TXT1'><![CDATA[ Lorem Ipsum ]]></text>
    <text id='TXT2'><![CDATA[ Lorem Ipsum ]]></text>
    <text id='TXT3'><![CDATA[ Lorem Ipsum ]]></text>
  </category>
</root>

PHP:

<?php  
$xml = simplexml_load_file('/path/to/text.xml');
$category = $xml->xpath("//category[@catid='1']/text");
$ids = ['TXT1', 'TXT2', 'TXT3'];

foreach($ids as $id){
  echo $category[$id]; //I'm not quite sure how to do this bit.
}
?>

Any help is appreciated, thanks!

Upvotes: 0

Views: 3261

Answers (2)

hek2mgl
hek2mgl

Reputation: 157967

Here comes an example how to do it using the DOM extension together with XPATH:

$doc = new DOMDocument();
$doc->loadXML($xml);

$selector = new DOMXPath($doc);

$result = $selector->query("//category[@catid='1']");
if($result->length !== 1) {
    die('BAD xml');
}

$category = $result->item(0);
$ids = array('TXT1', 'TXT2', 'TXT3');

foreach($ids as $id){
    // note $category as the second argument. meaning that the query
    // is relative to the category node and not to the root node
    $textResult = $selector->query("text[@id='$id']", $category);
    if($textResult->length < 1) {
        die('BAD xml');
    }

    $text = $textResult->item(0)->nodeValue;
    echo $text, PHP_EOL;
}

Upvotes: 2

Mihai8
Mihai8

Reputation: 3147

You can use DOMDocument::getElementById, for more see getElementById.

Upvotes: 1

Related Questions