PHP解析assoc.数组或XML


PHP parse assoc. array or XML

如何访问这个assoc数组?

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

作为XML解析的结果

<?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'};

//不工作-只回ID:1,为什么?}

//好吧,让我们换一种方式。。。

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

//打印结果-请参阅顶部的assoc阵列

//以及如何在这个(fck)assoc数组中访问订单id???

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

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

非常感谢您的帮助!

您想要的是:

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

现场演示

你的代码发生的事情是你试图循环:

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

这不是你想要的arrayorder-id是,正如你在垃圾堆上看到的那样:

Array
(
    [order-id] => Array