解析xml文件以获取列表

时间:2014-07-21 09:07:22

标签: xml xpath

我正在阅读XML以获取IATA的机场列表。

下面是xml:

array ( 0 => SimpleXMLElement::__set_state(array( 'airport' => 'Aalborg, Denmark ', 'code' => 'AAL', )), 1 => SimpleXMLElement::__set_state(array( 'airport' => 'Aalesund, Norway ', 'code' => 'AES', )), 2 => SimpleXMLElement::__set_state(array( 'airport' => 'Aarhus, Denmark - Bus service ', 'code' => 'ZID', )))

我试过了:

$list = $xml->xpath("//airport");
display_output($list[0]);

我得到了:

SimpleXMLElement::__set_state(array( ))

我怎么才能得到?

Aalborg, Denmark

1 个答案:

答案 0 :(得分:0)

数组不是xml。你能看一下githubusercontent的xml文件吗?

$ curl -s https://raw.githubusercontent.com/dodyg/AndroidRivers/master/assets/airports.xml | xmllint --xpath '//iata/iata_airport_codes[code="AAL"]' -
<iata_airport_codes>
        <airport>Aalborg, Denmark</airport>
        <code>AAL</code>
    </iata_airport_codes>

下面给出了您的示例输出;

$ curl -s https://raw.githubusercontent.com/dodyg/AndroidRivers/master/assets/airports.xml | xmllint --xpath '//iata/iata_airport_codes[code="AAL"]/airport/text()' -
Aalborg, Denmark

使用PHP获得相同的结果(获取数组的第一项);

$airport = $xml->xpath('//iata/iata_airport_codes[code="AAL"]/airport/text()')[0];
echo $airport