KlintWeb
KlintWeb

Reputation: 31

PHP foreach - parsed json from URL

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>';
}

?>

Upvotes: 1

Views: 2604

Answers (4)

Ian Lewis
Ian Lewis

Reputation: 1311

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()

Upvotes: 1

dialogik
dialogik

Reputation: 9552

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>';
}

Upvotes: 1

Rikesh
Rikesh

Reputation: 26431

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.

Upvotes: 1

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

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
}

Upvotes: 0

Related Questions