![]() I call a webservice from a JQuery $.getJSON function, it works fine. If you’re sending JSON data with PHP, I hope this might help! The CURLOPT_RETURNTRANSFER is purely so that the response from the remote server gets placed in $result rather than echoed. strlen($data_string))Īll these settings are pretty well explained on the curl_setopt() page, but basically the idea is to set the request to be a POST request, set the json-encoded data to be the body, and then set the correct headers to describe that post body. ![]() But now is it possible to return the data as JSON object. $data = array("name" => "Hagrid", "age" => "36") Ĭurl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST") Ĭurl_setopt($ch, CURLOPT_POSTFIELDS, $data_string) Ĭurl_setopt($ch, CURLOPT_RETURNTRANSFER, true) Ĭurl_setopt($ch, CURLOPT_HTTPHEADER, array( currently I have a php file that returns the data to the client via curl, I have changed the client to respond to JSON, to handle a problem and all works great. Instead, we create the correct JSON data, set that as the body of the POST request, and also set the headers correctly so that the server that receives this request will understand what we sent: So I post an encoded json to the index.php url which has no problem decoding it. We can’t send post fields, because we want to send JSON, not pretend to be a form (the merits of an API which accepts POST requests with data in form-format is an interesting debate). Im trying to take a login from my test.php file and cURL it to a site which uses the data to simulate a login on another page (I know this is tedious, but this isnt the full extent of what Im doing as a whole, just where I have the problem). After all, publishing your slides is all very well, but if you didn’t see the actual tutorial, I often think they aren’t too useful.ĮDIT: A more modern take on this topic is here If you are working on webservice and probable want to exchange data between two services/servers with an API, (i.e data from different web server to another) using PHP, curl is one. I got this question the other day: how to send a POST request from PHP with correctly-formatted JSON data? I referred to the slides from my web services tutorial for the answer, and I thought I’d also put it here, with a bit of explanation.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |