2013-08-28 32 views
0

如何访问此assoc数组?PHP parse assoc。数组或XML

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,为什么呢? }

// OK,让我们尝试另一种方式......

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

//打印结果 - 看到页面顶部assoc命令阵列

//以及如何存取权限在这个订单ID (fck)assoc数组???

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

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

很多感谢任何帮助!

+0

$ items ['order-id'] [0] and $ items ['order-id'] [1] –

+0

好吧,这似乎工作...以及如何使动态集合(迭代器)如果更多为了-ID(S)? – noh

+0

[欢迎使用StackOverflow,请参阅此处如何使用本网站](http://stackoverflow.com/about) – Prix

回答

1

你想要的是:

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

Live DEMO.

与您的代码会发生什么事是,你要循环:

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

这不是array你想要的, order-id是,正如你可以看到你的转储:

Array 
(
    [order-id] => Array 
+0

非常感谢@Prix!作品。 – noh