Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling data in a PHP JSON Object

Tags:

json

php

People also ask

How does JSON handle data in PHP?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.

Can PHP read JSON?

Parsing JSON with PHPPHP has built-in functions to encode and decode JSON data.

How do I access JSON data?

To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.


You mean something like this?

<?php

$jsonurl = "http://search.twitter.com/trends.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);

foreach ( $json_output->trends as $trend )
{
    echo "{$trend->name}\n";
}

If you use json_decode($string, true), you will get no objects, but everything as an associative or number indexed array. Way easier to handle, as the stdObject provided by PHP is nothing but a dumb container with public properties, which cannot be extended with your own functionality.

$array = json_decode($string, true);

echo $array['trends'][0]['name'];

Just use it like it was an object you defined. i.e.

$trends = $json_output->trends;