1

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

1

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

@AnneSchwarz But why would you want an array over an object. Objects are even easier to deal with than arrays
how so? objects are only easier if you actually have a true object with methods and whatnot. an object just to store some keys/values is essentially IDENTICAL to an array.
Well I always worked with normal arrays and I think they are easier to read/handle
Haha I must admit I like the fact you have 2 less keystrokes to ref a property and the code looks cleaner. Anyway, arnt we supposed to be in an Obect Oriented World

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.