Mark Johns II
Mark Johns II

Reputation: 11

Accessing Elements/Attributes From XML Using SimpleXML/PHP

Quick question: I'm using PHP's SimpleXML object to parse an XML file. For the life of me, I can't figure out how to access specific elements. My question is what would my PHP look like to access the nodes and the info contained in the "data" attributes? I don't want to iterate through the entire document, I only want specific information from the nodes. I tried the following with no luck:

$xml = simplexml_load_file("myXML.xml"); echo $xml->weather[0]->forecast_information->city->attributes()->data . "
";

Thanks in advance.

<xml_api_reply version="1">

<weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">

<forecast_information>
   <city data="Carlsbad, CA"/>
   <postal_code data="92009"/>
   <latitude_e6 data=""/>
   <longitude_e6 data=""/>
   <forecast_date data="2012-03-29"/>
   <current_date_time data="2012-03-29 11:52:00 +0000"/>
   <unit_system data="US"/>
</forecast_information>

<current_conditions>
   <condition data="Partly Cloudy"/>
   <temp_f data="62"/>
   <temp_c data="17"/>
   <humidity data="Humidity: 65%"/>
   <icon data="/ig/images/weather/partly_cloudy.gif"/>
   <wind_condition data="Wind: SW at 4 mph"/>
</current_conditions>


</weather>

</xml_api_reply>

Upvotes: 0

Views: 571

Answers (1)

Ren&#233; H&#246;hle
Ren&#233; H&#246;hle

Reputation: 27295

You can try with this code i have test it here:

$xml = new SimpleXMLElement(file_get_contents('xmltest.xml'));

var_dump($xml->weather->forecast_information->city);
echo ($xml->weather->forecast_information->city['data']);

the attributes of the elements like "data" can be accessed as array.

Notice: When you make a new Object you are in the first note in your case

<xml_api_reply version="1">

Upvotes: 1

Related Questions