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 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档