help parsing SimpleXMLElement

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
phpBever
Forum Commoner
Posts: 42
Joined: Fri Aug 07, 2009 10:23 am

help parsing SimpleXMLElement

Post 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.
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: help parsing SimpleXMLElement

Post 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;
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
phpBever
Forum Commoner
Posts: 42
Joined: Fri Aug 07, 2009 10:23 am

Re: help parsing SimpleXMLElement

Post by phpBever »

Great. That works. Thanks.
Post Reply