PHP - 迭代Additonial XML节点

时间:2016-04-20 00:48:31

标签: php xml simplexml

我正在使用以下XML响应结构:

<CompressedVehicles>
<F>
<RS> 
<R>
    <VS>
        <V />
        <V />
    </VS>
</R>
<R>
    <VS>
        <V />
        <V />
    </VS>
</R>
</RS>
</F>
</CompressedVehicles>

到目前为止,在Stack Overflow成员的指导下,我能够基于以下PHP代码构建一个可用的JSON输出:

header('Content-Type: application/json');

$xml  = simplexml_load_file( 'inventory.xml' );
$CompressedVehicles = $xml->CompressedVehicles;

$attributes = array();
foreach( $CompressedVehicles->F->attributes() as $key => $val )
{
    $attributes[$key] = $val->__toString();
}

$data = array();
foreach( $CompressedVehicles->F->RS->R->VS->V as $vehicle )
{
    $line = array();
    foreach( $vehicle->attributes() as $key => $val )
{
    $line[$attributes[$key]] = $val->__toString();
}
$data[] = $line;
}

$json = json_encode($data);
echo $json;

这只在完成之前迭代单个<R>节点。我现在如何附加代码以迭代每个<R>节点?

提前谢谢。

1 个答案:

答案 0 :(得分:1)

现在,您直接转到$http.post(ENDPOINT, $scope.selectionObject).then(function(success) { /* awesome */ }, function(error) { /* error */ }); ,只需将其修改为循环每个$CompressedVehicles->F->RS->R->VS->V节点:

<R>

这会迭代到每个foreach( $CompressedVehicles->F->RS->R as $r ) {

然后对于每个<R>,为<R>添加另一个嵌套:

$vehicle