1

I have a JSON file called from an URL. I've checked and I'm getting the the data from the URL.
I've tried a lot, but I can't get the loop foreach to work - what is wrong?

<?php

$url = 'http://banen.klintmx.dk/json/ba-simple-proxy.php?url=api.autoit.dk/car/GetCarsExtended/59efc61e-ceb2-463b-af39-80348d771999';
$json= file_get_contents($url);

$data = json_decode($json);
$rows = $data->{'contents'};
foreach($rows as $row) {
echo '<p>';
$FabrikatNavn = $row->{'contents'}->{'FabrikatNavn'};
$ModelNavn = $row->{'contents'}->{'ModelNavn'};
$PrisDetailDkk = $row->{'contents'}->{'PrisDetailDkk'};
echo $FabrikatNavn . $ModelNavn . ' Pris ' . $PrisDetailDkk;
echo '</p>';
}

?>
3
  • I've never seen a notation like this $data->{'contents'} in PHP. What is the error message? Commented Jun 11, 2014 at 12:21
  • 4
    You can replace $data->{'contents'} with $data->contents. The syntax is used, if you want to access dynamic properties, like $data->{$otherVar} Commented Jun 11, 2014 at 12:24
  • @bali182 - That will work too. Commented Jun 11, 2014 at 12:30

4 Answers 4

1

The actual problem is you trying to access content object again. Just change your foreach snippet with,

foreach ($rows as $row) {
    echo '<p>';
    $FabrikatNavn = $row->FabrikatNavn;
    $ModelNavn = $row->ModelNavn;
    $PrisDetailDkk = $row->PrisDetailDkk;
    echo $FabrikatNavn . $ModelNavn . ' Pris ' . $PrisDetailDkk;
    echo '</p>';
}

DEMO.

Sign up to request clarification or add additional context in comments.

Comments

1

Use json_decode($data, true) so that it parses the JSON content into a PHP array. So it will be something like

$rows = $data['contents'];
foreach($rows as $row) {
    echo '<p>';
    $FabrikatNavn = $row['contents']['FabrikatNavn'];
    $ModelNavn = $row['contents']['ModelNavn'];
    $PrisDetailDkk = $row['contents']['PrisDetailDkk'];
    echo $FabrikatNavn . $ModelNavn . ' Pris ' . $PrisDetailDkk;
    echo '</p>';
}

2 Comments

json_decode($contents, true) does what you said. otherwise the associative parts will be objects.
Thanks for the info, didn't know that. I modified my answer accordingly.
1

Take a look at using json_decode($json, true) as this will convert the data to an associative array which seems to be the way you are approaching the solution.

Check the output by printing with var_dump() or print_r()

Comments

0

Try like this

$data = json_decode($json,true); //decode json result as array and thenloop it
print '<pre>';
print_r($data);
foreach($data as $row){
//do something here
}

Comments

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.