0

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.

1
  • don't point it directly into V, cut it to each R, so nest another loop, first loop until R first, then each piece of R then point to VS->V Commented Apr 20, 2016 at 0:55

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

THANK YOU! I stared and messed with it for over an hour and missed something that simple.
@proph3t sure glad this helped

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.