PHP - 通过其他XML节点迭代

I am working with the following XML response structure:

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

So far, with guidance from a fellow Stack Overflow member, I was able to construct a working JSON output based on the following PHP code:

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;

This only iterates through a single <R> node before completion. How can I now append the code to iterate through each <R> node as well?

Thank you in advance.

Right now, you're directly going to $CompressedVehicles->F->RS->R->VS->V, just modify it to loop each <R> node:

foreach( $CompressedVehicles->F->RS->R as $r )
{

This iterate to each <R>.

Then for each <R>, add another nest for the $vehicle:

foreach($r->VS->V as $vehicle) 
{
// rest of your code