下面是我用来将xml转换为数组
的函数$xml = '<xml><CodeshareInfo OperatingCarrier="EY" OperatingFlightNumber="269">ETIHAD AIRWAYS</CodeshareInfo></xml>';
$obj = simplexml_load_string($xml); // Parse XML
$obj->registerXPathNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
$array = json_decode(json_encode($obj), true); // Convert to array
当我尝试使用父节点“xml”
时<xml><CodeshareInfo OperatingCarrier="EY" OperatingFlightNumber="269">ETIHAD AIRWAYS</CodeshareInfo></xml>
我得到了这个结果
Array
(
[CodeshareInfo] => ETIHAD AIRWAYS
)
但如果我尝试没有父节点“xml”
<CodeshareInfo OperatingCarrier="EY" OperatingFlightNumber="269">ETIHAD AIRWAYS</CodeshareInfo>
我可以获得属性和值
Array
(
[@attributes] => Array
(
[OperatingCarrier] => EY
[OperatingFlightNumber] => 269
)
[0] => ETIHAD AIRWAYS
)
我应该在代码中更改以获取具有属性和值的输出,因为我的xml数据来自soap请求,一旦我收到,我将转换为数组以访问其值和属性。
答案 0 :(得分:0)
鉴于提供的XML,您可以迭代它并提取属性和值。
<?php
$xml = '<xml><CodeshareInfo OperatingCarrier="EY" OperatingFlightNumber="269">ETIHAD AIRWAYS</CodeshareInfo></xml>';
$obj = simplexml_load_string($xml); // Parse XML
$obj->registerXPathNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
foreach($obj as $ob) {
echo $ob['OperatingCarrier'] . "\n";
echo $ob . "\n";
echo $ob['OperatingFlightNumber'] . "\n";
}
输出:
EY
ETIHAD AIRWAYS
269个