views:

137

answers:

3

I have a small XML file:

<wddxPacket version='1.0'>
  <header/>
  <data>
    <struct type='coldfusion.runtime.ArgumentCollection'>
      <var name='HEADLINE'>
        <string>Richard Barret's Articles on Leadership and High Performance Organisations</string>
      </var>
    </struct>
  </data>
</wddxPacket>

I'm trying to use PHP SimpleXML and xpath to extract the value between the string element in the var name HEADLINE element. This code works:

// Location of the XML file on the file system
$file = 'http://10.10.200.37/skins/importscript/41802.xml';
$xml = simplexml_load_file($file);

// CREATE THE ARRAYS FOR EACH XML ELEMENT NEEDED

$title = $xml->xpath('//var[@name="HEADLINE"]');

echo "<p>";
print_r($title);
echo "</p>";

The problem is that it returns not only the value but also all the array information. As in:

Array ( 
  [0] => SimpleXMLElement Object ( 
    [@attributes] => Array ( 
      [name] => HEADLINE 
    ) 
    [string] => Richard Barret's Articles on Leadership and High Performance Organisations
  )
)

How can I get it to return just the value and nothing else?

If I replace print_r with echo $title; I get the word Array on the page instead of the value. If I try echo $title[0]; I get nothing at all.

I've tried so many things now can't think of anything else! What am I doing wrong? Could anyone point me in the right direction? Thanks!

+8  A: 

Sorry please ignore this! Just after I posted the question I realised what I was doing wrong!

For anyone being as slow as I am today here was the problem...

$title = $xml->xpath('//var[@name="HEADLINE"]');

Should be:

$title = $xml->xpath('//var[@name="HEADLINE"]/string');

Now it works as it should.

Johannes
+1. One more up-vote and your first earned badge on Stack Overflow is [Self-Learner]. This would put you in a rather exclusive circle - currently, only 262 of more than 117,000 users have it. ;)
Tomalak
+2  A: 

You are interested in the nodeValue.

Example:

$xpath->evaluate("some_tag_name", $some_dom_element)->item(0)->nodeValue;

or use the string selector:

$title = $xml->xpath('//var[@name="HEADLINE"]/string');
The MYYN
A: 

As a habit I always add the 'string' type when getting values from SimpleXML

$title = (string) $xml->xpath('//var[@name="HEADLINE"]/string');

Not sure if this is good practice..

chameleon95