解析 PHP 中的 XML 错误


Parse XML in PHP error

过去我用<station></station>标签加载了xmlfile,并做了一个像这样的foreach循环

foreach ( $xml->station as $item )
{
...
}>

现在我得到了这样的新结构,它不再起作用了。你能帮帮我吗?

<stations>
<station id="1" name="Raumschiff1" strasse="Musterstrasse 1" plz="11011" ort="Berlin" lat="50.77548" lng="6.08147" operator="NEO" telefon="0800 MATRIX" zugang="ZION"/>
<station id="2" name="Raumschiff1" strasse="Musterstrasse 1" plz="11011" ort="Berlin" lat="50.77548" lng="6.08147" operator="NEO" telefon="0800 MATRIX" zugang="ZION"/>
</stations>

提前非常感谢! :-)

  • 已添加simplexml_load_string()
  • 如果需要加载文件$xml = simplexml_load_file('test.xml');
  • 添加了缺少 XML 文档类型行。

示例如下:

$xml_string = '<?xml version="1.0" encoding="UTF-8"?>
<stations>
  <station id="1" name="Raumschiff1" strasse="Musterstrasse 1" plz="11011" ort="Berlin" lat="50.77548" lng="6.08147" operator="NEO" telefon="0800 MATRIX" zugang="ZION" />
  <station id="2" name="Raumschiff2" strasse="Musterstrasse 1" plz="11011" ort="Berlin" lat="50.77548" lng="6.08147" operator="NEO" telefon="0800 MATRIX" zugang="ZION" />
</stations>';
$xml = simplexml_load_string($xml_string);    
//print_r($xml);
// iterate over the SimpleXMLElement Object    
foreach($xml->station as $station) {
    // you need to take the attributes into account
    foreach ($station->attributes() as $attributeName => $attributeValue) {
        printf("'n%s => %s", $attributeName, $attributeValue);
    }
    echo "<hr>";
}


你的下一个问题是:"如何迭代该对象或数组?

已经回答:

  • 如何循环访问作为 SimpleXMLElement 对象的 XML 值
  • 循环遍历 SimpleXML 对象,或将整个对象转换为数组