Reputation: 377
I'm using PHP to connect to an API and register some info using JSON and HTTP POST but it is not going well.
That is what I do:
I create a JSON object with the json_encode function:
$name = 'Mike';
$surname = 'Hans';
$fields = array('name' => json_encode($name), 'surname' => json_encode($surname));
$postData = json_encode($flds);
Once i have the post data, I just connect to the API with curl and login with oauth, but the API responde says:
JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this)
I have checked the allow_nonref in Google, but i could not find anything for PHP, all I have found is for Perl. Does anyone have any solution/advice to solve this?
Thanks!
Upvotes: 0
Views: 5753
Reputation:
To follow up on @nickb's answer, please only use one call to json_encode
, it's far better at constructing valid json that you and I are, and it's more efficient to boot! (though we are entering the realm of micro-optimisation).
Have you tried taking the output of the json_encode
and putting it into a validator/formatter such as the one here : http://jsonviewer.stack.hu/
Also, I think another likely problem could be the headers you are sending? The recieiving server could be strict and enforce that you use the correct 'Content-Type'. Are there any API docs avaliable?
Upvotes: 0
Reputation: 59699
You probably need to send the entire POST as JSON without nesting calls to json_encode
, like this:
$fields = array('name' => $name, 'surname' => $surname);
$postData = json_encode( $fields);
Upvotes: 1