Eddy Unruh
Eddy Unruh

Reputation: 616

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?!

Upvotes: 1

Views: 1484

Answers (1)

Marc B
Marc B

Reputation: 360702

JSON's definition is: JavaScript Object Notation. JavaScript 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().

Upvotes: 2

Related Questions