PHP - 迭代额外的 XML 节点
PHP - Iterate Though Additonial XML Node
我正在使用以下 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
我正在使用以下 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