Anne Schwarz Anne Schwarz - 4 months ago 11
JSON Question

How to create JSON response in PHP file?

I'd like to get JSON response on my second server with the domain

example.com
where the
getit.php
file contains:

$arr = array('antwort' => 'jo');

echo json_encode($arr);


Now when I try to get it with my first server:

$url = 'http://www.example.com/getit.php';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$antwort = curl_exec($ch);
curl_close($ch);

$antwort = json_decode($antwort);

echo '<pre>';
var_dump($antwort);
echo '</pre>';


I get:

object(stdClass)#2 (1) {
["antwort"]=>
string(4) "jo"
}


And not an normal array, how do I convert this to array?

I allready tried
$antwort = json_decode(json_encode($antwort), True);
but I only get a weird string with that?!

Answer

JSON is basically JavaScsript. Javascsript arrays can only have numeric keys. Your array has string keys, therefore it MUST be encoded as a Javascript OJBECT, which do allow string keys.

Tell json_decode() you want arrays instead:

$arr = json_decode($json, true);
                          ^^^^

as per the docs

Where how did you do your json_decode(json_encode($antwort))? The ONLY way that'd return a string is if you encoded the $antwort you'd gotten from curl_exec().