Anne Schwarz Anne Schwarz - 6 months ago 15
JSON Question

How to create JSON response in PHP file?

I'd like to get JSON response on my second server with the domain
where the
file contains:

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

echo json_encode($arr);

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

$url = '';

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

$antwort = json_decode($antwort);

echo '<pre>';
echo '</pre>';

I get:

object(stdClass)#2 (1) {
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?!


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