Page 1 of 1

help parsing SimpleXMLElement

Posted: Thu Jan 06, 2011 9:55 am
by phpBever
I'm getting back an XML which I'm looking at as a SimpleXMLElement:

Code: Select all

  $xmlFileData = file_get_contents($url);
  $Data = new SimpleXMLElement($xmlFileData);
  echo "First Name is $firstName";
  echo "<br />";
  echo "<pre>";
  print_r($Data);
  echo "</pre>";
it prints nicely to a page using the print_r($Data) command. But I'm confused about how to access the actual values. For example, part of the print_r output looks like this:
SimpleXMLElement Object
(
[legislators] => SimpleXMLElement Object
(
[legislator] => Array
(
[0] => SimpleXMLElement Object
(
[website] => http://house.gov/velazquez/
[fax] => 202-226-0327
[govtrack_id] => 400416
[firstname] => Nydia
[chamber] => house
[middlename] => M.
I've tried various ways to access the actual values, without success. I'm confused by the multiples levels in the returned $Data object

Code: Select all

  $firstName = $Data->[legislators][legislator][0][firstname];;
  //$firstName = $Data[legislators][legislator][0][firstname];
  //echo "First Name is $Data[legislators][legislator][0][firstname=>value]";
Can someone show me the correct syntax?
Thanks.

Re: help parsing SimpleXMLElement

Posted: Thu Jan 06, 2011 10:14 am
by AbraCadaver
Try this (everything except legislator is an object, legislator is an object property but the only array):

Code: Select all

$firstName = $Data->legislators->legislator[0]->firstname;

Re: help parsing SimpleXMLElement

Posted: Thu Jan 06, 2011 10:18 am
by phpBever
Great. That works. Thanks.