Raphael Jeger
Raphael Jeger

Reputation: 5232

Get XML-node by attribute name

I have the following XML-structure:

   <Folder>
      <Placemark>
        <ExtendedData>
          <Data name="Id">
            <value>152285415</value>
          </Data>
          <Data name="Name">
            <value>Tester</value>
          </Data>
        </ExtendedData>
      </Placemark>
    </Folder>

and I need to directly access the of the -Object with the attribute "name" = "Id".

So I tried this:

$xml->Document->Folder->Placemark->ExtendedData->xpath('data[@name="Id"]')

but that gives and empty array.

What I need in the end is "152285415"

Any help appreciated.

Upvotes: 1

Views: 65

Answers (3)

Nigel Ren
Nigel Ren

Reputation: 57141

To not worry about the overall hierarchy of the document (although this is abused quite a bit) is to use // as the first part of the XPath. So the query can be written as in...

<?php
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );

$xmlDoc = <<<XML
<Folder>
  <Placemark>
    <ExtendedData>
      <Data name="Id">
        <value>152285415</value>
      </Data>
      <Data name="Name">
        <value>Tester</value>
      </Data>
    </ExtendedData>
  </Placemark>
</Folder>
XML;

$xml = new SimpleXMLElement($xmlDoc);
$value = $xml->xpath('//Data[@name="Id"]/value')[0];
echo "Value=".$value.PHP_EOL;

Although note that $value is still a SimpleXMLElement Object, so if you need it as a string, you should use (string)$value. In the example, echo will automatically do the conversion for you.

Upvotes: 0

ishegg
ishegg

Reputation: 9957

You can use XPath to access what you want directly:

<?php
$xml = '<Folder>
      <Placemark>
        <ExtendedData>
          <Data name="Id">
            <value>152285415</value>
          </Data>
          <Data name="Name">
            <value>Tester</value>
          </Data>
        </ExtendedData>
      </Placemark>
    </Folder>';

$xml = new SimpleXMLElement($xml);
$result = $xml->xpath('/Folder/Placemark/ExtendedData/Data[@name="Id"]');
echo "Value: ".$result[0]->value; // Value: 152285415

Demo

Upvotes: 1

Chris
Chris

Reputation: 4748

This seems to do the job:

<?php

$xml = '<Folder>
      <Placemark>
        <ExtendedData>
          <Data name="Id">
            <value>152285415</value>
          </Data>
          <Data name="Name">
            <value>Tester</value>
          </Data>
        </ExtendedData>
      </Placemark>
    </Folder>';

$xml = simplexml_load_string($xml);

foreach($xml->Placemark->ExtendedData->Data as $item) {

    if($item->attributes()['name'] == 'Id') {
        echo $item->value;
    }

}

Upvotes: 1

Related Questions