doutan1905 2013-08-28 22: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 23: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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 虚心请教几个问题,小生先有礼了