我正在使用以下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>
节点?
提前谢谢你。
现在,你直接要$CompressedVehicles->F->RS->R->VS->V
,只需修改它以循环每个<R>
节点:
foreach( $CompressedVehicles->F->RS->R as $r )
{
这将迭代到每个<R>
。
然后对于每个<R>
,为$vehicle
添加另一个嵌套:
foreach($r->VS->V as $vehicle)
{
// rest of your code