0

I have the following XML file:

<?xml version="1.0" encoding="UTF-8"?>
<result name="response">
    <doc>
        <str name="index">2</str>
        <str name="summary">A summary</str>
        <str name="title">A Title</str>
        <arr name="media">
            <str>/image/123.jpg</str>
        </arr>
    </doc>
</result>

I'm grabbing the contents and creating a SimpleXMLElement in PHP. I need to be able to grab the contents of a specific tag based on it's name value. E.g. If I was trying to echo out "A summary" something like this:

echo $xmlObj->doc->str['name']->summary;

I know that doesn't work but what will? I've looked at a lot of similar questions but haven't found one with this specific problem. Cheers.

igneosaur
  • 3,268
  • 3
  • 29
  • 44
  • 2
    You will need to either loop through all elements (`foreach ( $xmlObj->doc->str ...`) to find the one with the name you want, or use an XPath expression. Note that there will be no `$xmlObj->result` in the example you show - `$xmlObj` itself will represent the root `` node. – IMSoP Jun 11 '14 at 09:13
  • Ok, I'll have a look into XPath. Ah, and thanks for the correction. – igneosaur Jun 11 '14 at 09:18
  • It's similar, but not quite a duplicate. One of the "incorrect" answers from that question is the correct answer to this one. – igneosaur Jun 11 '14 at 10:50
  • @IMSoP: Remind me we should create some PHP related blogposts on the SO platform. – hakre Jun 12 '14 at 22:45

2 Answers2

1

Use XPath (http://www.w3schools.com/php/func_simplexml_xpath.asp)

<?php
$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";
}
?>
a4arpan
  • 1,828
  • 2
  • 24
  • 41
1

The solution to the problem is as follows:

$summary = $xmlObj->xpath('doc/str[@name="summary"]');

if($summary) {
    echo $summary[0];
}

It involves using XPath as a4arpan pointed out.

Community
  • 1
  • 1
igneosaur
  • 3,268
  • 3
  • 29
  • 44