2012-03-29 65 views
0

快速问题:我正在使用PHP的SimpleXML对象来解析XML文件。对于我来说,我无法弄清楚如何访问特定的元素。我的问题是我的PHP看起来像访问包含在“data”属性中的节点和信息?我不想遍历整个文档,我只想要来自节点的特定信息。我尝试了以下运气:使用SimpleXML/PHP从XML访问元素/属性

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

在此先感谢。

<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> 

回答

1

您可以使用此代码尝试我在这里测试:

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

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

像“数据”元素的属性可以作为数组访问。

注意:当你犯了一个新的对象,你是第一个音符在你的情况

<xml_api_reply version="1"> 
+0

石溪,工作就像一个魅力。感谢您的帮助,非常感谢!祝你周末愉快... – 2012-03-29 14:09:51

+0

@Mark Johns II:没问题。当你不知道如何获取价值观时,我知道它非常重要。如果现在解决了,也许你可以接受它作为正确的答案。 – Stony 2012-03-29 14:48:43