2

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.

2
  • 2
    You need to use xpath; the syntax is almost exactly like you wrote it. Commented Dec 20, 2012 at 23:05
  • Thanks. Any possibility to make it work the way I have it actually? Commented Dec 20, 2012 at 23:07

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

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.