在PHP中解析XML错误

时间:2015-01-14 14:18:54

标签: php xml parsing

过去我使用<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>

提前多多感谢! : - )

1 个答案:

答案 0 :(得分:0)

  • 添加了simplexml_load_string()
  • 如果您需要加载文件$xml = simplexml_load_file('test.xml');
  • 添加了xml doctype行缺失。

以下示例:     

$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>";
}

您的下一个问题是:&#34;如何迭代该对象或数组?&#34;

已经回答: