doutan1905 2013-08-28 14:26
浏览 28
已采纳

PHP解析关联。 数组或XML

How to acces this assoc array?

Array
(
    [order-id] => Array
       (
           [0] => 1
           [1] => 2
       )

)

as a result of XML parsing

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE request SYSTEM "http://shits.com/wtf.dtd">
<request version="0.5">
<order-states-request>
    <order-ids>
        <order-id>1</order-id>
        <order-id>2</order-id>
          ...
    </order-ids>
 </order-states-request>
</request>


$body = file_get_contents('php://input');
$xml = simplexml_load_string($body);

$src = $xml->{'order-states-request'}->{'order-ids'};
foreach ($src as $order) {
     echo ' ID:'.$order->{'order-id'};

// dont work - echoes only ID:1, why? }

// ok, lets try just another way...

$items = toArray($src); //googled function - see at the bottom
print_r($items);

// print result - see at the top assoc array

// and how to acces order ids in this (fck) assoc array???

//------------------------------------------

function toArray(SimpleXMLElement $xml) {
    $array = (array)$xml;

    foreach ( array_slice($array, 0) as $key => $value ) {
        if ( $value instanceof SimpleXMLElement ) {
            $array[$key] = empty($value) ? NULL : toArray($value);
        }
    }
    return $array;
}

MANY THANKS FOR ANY HELP!

展开全部

  • 写回答

1条回答 默认 最新

  • dsa4d4789789 2013-08-28 15:17
    关注

    What you want is:

    $body = file_get_contents('php://input');
    $xml = simplexml_load_string($body);
    $src = $xml->{'order-states-request'}->{'order-ids'}->{'order-id'};
    foreach ($src as $id)
    {
         echo ' ID:', $id, "
    ";
    }
    

    Live DEMO.

    What happens with your code is that you're trying to loop:

    $xml->{'order-states-request'}->{'order-ids'}
    

    Which is not the array you want, order-id is, as you can see on your dump:

    Array
    (
        [order-id] => Array
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部