【问题标题】:Accessing Elements/Attributes From XML Using SimpleXML/PHP使用 SimpleXML/PHP 从 XML 访问元素/属性
【发布时间】:2012-04-13 04:14:00
【问题描述】:

快速提问:我正在使用 PHP 的 SimpleXML 对象来解析 XML 文件。对于我的生活,我无法弄清楚如何访问特定元素。我的问题是我的 PHP 会是什么样子来访问“数据”属性中包含的节点和信息?我不想遍历整个文档,我只想要来自节点的特定信息。我尝试了以下方法,但没有成功:

$xml = simplexml_load_file("myXML.xml"); 回声 $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>

【问题讨论】:

    标签: php xml simplexml


    【解决方案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">
    

    【讨论】:

    • Stony,工作就像一个魅力。感谢您的帮助,不胜感激!周末愉快……
    • @Mark Johns II:没问题。当您不知道如何访问这些值时,我知道它非常有用。如果现在解决了,也许您可​​以接受它作为正确答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2014-04-26
    • 1970-01-01
    相关资源
    最近更新 更多