0

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:

  1. 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);
    
  2. 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!

1
  • 2
    Why would you encode them separately, then encode them together? Commented Nov 29, 2011 at 6:18

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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?

Comments

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.