Display content from a JSON using PHP and separate fields

Asked

Viewed 8,131 times

1

I have the URL of an API that generates a JSON. I have this code below, however I need separate fields for me to be able to create while of the items and to separate type echo $row['nome_marca'] and etc. Some light?

<?php
header("Content-Type: application/json");
$jsonData = file_get_contents("http://www.folhacar.com.br/frontendnovo.php/api/listMarcas");
echo $jsonData;
?>
  • From what I understand you want to decode JSON. You need this in PHP itself, or it would be at the other end, in Javascript?

  • have you tried using php’s json_decode function? This would give you an array - http://php.net/json_decode

  • I haven’t tried yet because I don’t have much intimacy with php, but I need to resolve this. Could you give me an example of how I can individually use this array after the implementation?

2 answers

4


To read the data of a JSON you can use the json_decode function. See:

<?php
    $json = json_decode(file_get_contents("http://www.folhacar.com.br/frontendnovo.php/api/listMarcas"));
    for($i = 0; $i < count($json); $i++) {
        echo "<div>ID: " . $json[$i]->{'marca_id'} . "</div>";
        echo "<div>Marca: " . $json[$i]->{'nome_marca'} . "</div>";
        echo "<br />";
    }
?>

The json_decode function will return an array. Then, just use for() to scroll through and process the data.

  • Great Jhonas, exactly what I need to do. Thank you very much for your attention!!!

0

Use PHP’s json_decode function to turn your json string into something more readable in PHP.

In this your output (json) would be an array

http://php.net/json_decode

<?php
header("Content-Type: application/json");
$jsonData = file_get_contents("http://www.folhacar.com.br/frontendnovo.php/api/listMarcas");
$arrData = json_decode($jsonData); // Transforma o seu JSON
// print_r($arrData);

foreach ($arrData as $indiceDoArray => $valorDoArray) {
    echo "Elemento na posição {$indiceDoArray} tem valor {$valorDoArray}<br>";
}
?>
  • Perfect, but this is where I get it: <br /> <b>Notice</b>: Array to string Conversion in <b>/Applications/MAMP/htdocs/proveiculos/teste.php</b> on line <b>4</b><br /> Array How do I use this array? like "echo $Row[field'];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.