inrob
inrob

Reputation: 5089

parsing xml data from php

So I haven't any experience on xml reading with php, I've been doing some research,read some tutorials but there's one thing I'd like to make sure of. Now I have this xml code below (file.xml):

  <location code="TB0023">
    <temp unit="F">15.8</temp>
    <US>Intermittent clouds</US>
  </location>

  <location code="YG0023">
    <temp unit="F">23</temp>
    <US>Mostly Clear</US>
  </location>

So the way I access for example temp on location code="TB0023" is this:

$open = simplexml_load_file('file.xml');
echo $open ->location[0]->temp;

Now I've unsuccessfully trying to make it a bit more readable by doing something like this(like associative arrays somehow):

$open = simplexml_load_file('file.xml');
echo $open ->location[code="TB0023"]->temp;

So is there any way to use that identifier TB0023 to retreive data from that specific location, without using indexes 0 1 2 3...

Thank you.

Upvotes: 2

Views: 87

Answers (2)

SteAp
SteAp

Reputation: 11999

The SimpleXML framework contains a SimpleXMLElement class.

Please use SimpleXMLElement's path() method with Xpath expressions described here.

This code from the php.net site

$string = <<<XML
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <d>
  <c>code</c>
 </d>
</a>
XML;

$xml = new SimpleXMLElement($string);

/* Search for <a><b><c> */
$result = $xml->xpath('/a/b/c');

while(list( , $node) = each($result)) {
    echo '/a/b/c: ',$node,"\n";
}

/* Relative paths also work... */
$result = $xml->xpath('b/c');

while(list( , $node) = each($result)) {
    echo 'b/c: ',$node,"\n";
}

will print this:

/a/b/c: text
/a/b/c: stuff
b/c: text
b/c: stuff

XPath is the standard technique to locate elements within XML.

In your case, you'd use an xpath query like this:

/location[@code="TB0023"]/temp

Upvotes: 1

Kevin Barnard
Kevin Barnard

Reputation: 99

You want to use xpath to query the value in the XML.

$result = $open->xpath("//location[@code='TB0023']")

You can find more in the PHP documents XPath

Upvotes: 1

Related Questions