Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用PHP处理XML_Php_Xml_Simplexml - Fatal编程技术网

用PHP处理XML

用PHP处理XML,php,xml,simplexml,Php,Xml,Simplexml,我有一个XML示例数据 <Stations> <Station> <Code>HT</Code> <Type>knooppuntIntercitystation</Type> <Namen> <Kort>H'bosch</Kort> <Middel>'s-Hertogenbo

我有一个XML示例数据

<Stations>
    <Station>
        <Code>HT</Code>
        <Type>knooppuntIntercitystation</Type>
        <Namen>
            <Kort>H'bosch</Kort>
            <Middel>'s-Hertogenbosch</Middel>
            <Lang>'s-Hertogenbosch</Lang>
        </Namen>
        <Land>NL</Land>
        <UICCode>8400319</UICCode>
        <Lat>51.69048</Lat>
        <Lon>5.29362</Lon>
        <Synoniemen>
            <Synoniem>Hertogenbosch ('s)</Synoniem>
            <Synoniem>Den Bosch</Synoniem>
        </Synoniemen>
    </Station>
</Stations>
下面是PHP代码:

$data = simplexml_load_file("includes/assets/xml/ns_test.xml");
    foreach($data->children() as $station => $value){
        foreach($value as $key){
            print_r($key['lon']);
            print_r($key['lat']);
        }
    }
问题是要么我得到了
simplexmlement Object()
,什么都没有,要么像
这样的错误试图得到非Object的属性。

我想从我的国家火车公司的旧skool XML文件中收集数据,我希望他们能将数据导出为JSON。

你把这件事弄得太复杂了,直接访问属性就行了

foreach ($data->children() as $station => $value) {
    //at this point, $value is the first <Station>
    echo $value->Lat . "\n"; //thus you can access Lat from the first Station with ->
    echo $value->Lon; //same with Lon
}
三个问题:

  • 外部循环已经在
    元素上循环
  • XML区分大小写:
    Lon
    不等于
    Lon
  • 使用
    $parent->$childname
    访问子元素
  • 改用这个:

    foreach($data->children() as $station => $value){
      print_r($value->Lon);
      print_r($value->Lat);
    }
    
    foreach($data->children() as $station => $value){
      print_r($value->Lon);
      print_r($value->Lat);
    }