json_decode with file_get_contents - php

I am trying to use PHP to echo the contents as plain text so that I can use it my application.
I am trying to obtain the contents of http://www.revctrl.com/api/projects/231 which is in jSON format then convert it to an associated array then manually echo the contents in a nice and neat format. But for some reason, file_get_contents is returning NULL everytime.
I have no clue what is wrong with the code.
$jsonData = json_decode(file_get_contents("https://www.revctrl.com/api/projects/231"), true);
The link works in the browser. The jSON output is valid (checked using http://jsonlint.com/).
Any idea why I get a null from file_get_contents?
Is there any server setting that needs to be set to allow outside links to be accessible?

file_get_contents just discards the server response body in case the HTTP status code indicates the some kind of error; and standard PHP error reporting won’t give you a much of a clue either in case you’re using the function to make an HTTP request.
You can pass in an HTTP context via stream_context_create, setting the option ignore_errors to true – then you will get the error message description the server has likely send in the response body returned.
Use var_dump to output it – then you should be able to figure out what goes wrong on the remote end.

Related

Postman returns 404, while website returns 200

I have a Laravel sever serving an api at http://localhost:8000/api/v1_0/login.
This API when hit from the web page (a login form) works fine with 200 OK status, however when I try to hit the same API with Postman, it returns me 404. I'm sure that my headers and URL spellings are correct. Is this a bug? what else could be the reason?
Just in case someone still need an answer for this. I checked the answer posted by #ZI3n but the solution didn't worked for me.
Postman was receiving a String text\html which is a default Content-Type so I suspected the code I used to processed the JSON was, somehow, forming a string not recognized by Postman as a JSON. But when was received I could see it as JSON, if changed the body type to JSON.
Because of this the request was being received as JSON formatted text but was not recognized as a JSON content, and since I was expecting a JSON the status code was ignored and replaced with 404 Not Found. Not sure if this was by the server or Postman.
So I visited the URL directly on the browser, and it was obvious that the JSON was displayed but still read as text/html and not as application/json
The next step was to refactor the code again, this time I reprocessed the JSON string by assigning the string to a variable $json as follow:
//assigning previous json string to $json
$json = $originalEchoedJsonString;
//reprocessing the string a converting it back to object
$newJson = json_decode($json);
//preparing to be send
//if PHP version 5.4+
http_response_code(200);
// Any PHP version specially 5.3 and under
header('HTTP/1.1 200 Ok', true, 200);
header('Content-type: application/json; charset=UTF-8;');
//echoing JSON back with json_encode();
echo json_encode($newJson);
After doing this I sent the request with Postman again and voila, I got a 200 Ok status and the string was properly displayed as a JSON file. Also was recognized by the browser JSON formatter as a JSON.
I know this is a very old question, but for future people with this problem I'll add this.
On the Headers tab, there is a Host header option. If it is not checked then the server may not accept the request and return an error. In my case a 404 rather than the 400 shown in the postman tooltip below.
Curl and browsers do add it automatically, which is why they can behave differently when this option is not checked.

PHP Unirest plugin not working properly

I use Unirest for PHP to do some HTTP Requests. Everything works fine, until I want to pass a fairly complex JSON to my Node.js router.
First I do a GET request that returns a JSON Object, then I extend this JSON object (needs to be done, I know it sucks) and want to feed it back into my other http POST request... and here is where the trouble starts:
I echoed the JSON that is returned and copied the output into postman -> works fine. If I want use the JSON directly in PHP in next request:
$teamsMemberOf is the variable which is containing the GET response.
$headers = array("Accept" => "application/json");
$newBody = '{"team":'.$teamsMemberOf->raw_body.'}';
$relevantBoxesAmount = Unirest\Request::post("http://localhost:3001/my/route/".$result['_id']."/get-something-from-server", $headers, $newBody);
and it doesn't work.
Error is 500 and 'Cannot read property '0' of undefined' which is certainly related to something in the JSON object.
Does someone have an idea how to fix it?

Weird response from Exact Online API using Auth 2.0

I was able to download some PHP code from exact online to connect to their API. Using this, I get logged in and get all the data such as my access token.
Now, when I do a simple http get on start.exactonline.nl/api (exactly as stated on their website), I get a 755 character string back with no meaning to me at all. Below a part of this string, just as an example, the original string I get back is way longer.
¶¨ÿ}6^¾œïvt6ù’Ì>L!3EOï>%àJ¿÷J'ó ü¸ßßAèðh”H ¥ÓÏx™1ëˆÒÝnçïú~©Vtþ•îèÍ”è ãsýëvkäÎa_äRÿÇÃ#ãTaàôþÞˆíØKiP2?¬Ñƒ´^=ƒ{CBiÆ”F3º$WWƒ! =ꨌ09^!x’lc²R‰?È#¸ISÔ„ŽR ¾A0%Q/­Q¢­\äÀ¢^.ËxÁÒ+Un$:ÓjÄÏíÖR`ÎmØãšq.ä* ¬÷îagñ3´[Yx|ÕïùÖÀ‹±´ÌKuf³™
I should actually get an Json package back I suppose, or an error message, but I get this back.
Has anybody have a clue as to what is going on here or what I could check?
Make sure you add CURLOPT_ENCODING => '' to your cURL call, what you're receiving is a raw gzipped file.

Sending a call to facebook graph api does not return anything when an error occurs

I am using graph api to get a list of albums of a user. Now in case the user signs out or has changes password or any error condition, I do not get any response whereas some error code should be returned. The graph API url when opened in the browser shows the error but on using file_get_contents() i get error 400. On using curl, I get an empty response. Is there any way that I can find out when an error occurs and the reason for it?
The graph API url when opened in the browser shows the error but on using file_get_contents() i get error 400.
Well, that is the HTTP status code that Facebook sends with Oauth errors – nothing wrong about that.
But file_get_contents by default does not show you the actual HTTP response body content in case of an HTTP status codes that signals an error …
… which is just another reason, why one should use the official PHP SDK, which handles all of that nicely and presents you with an exception that tells you exactly what is up.
So do it, please.
(Even with file_get_contents one can get the body content of the response, when setting a “stream context” with the according option first. But using the PHP SDK is way simpler, so again: Please do it.)
I used curl instead of file_get_contents and the issue got resolved.
file_get_contents() gave me error many times when I put https instead of http or If I forgot to put any of them.
Your URL from which you get the content must have "http" at the starting, like:
file_get_contents("http://www.mysite.com");
If this solves it?

Receive JSON object from HTTP Get in PHP

I am trying to implement a php client that sends an HTTP GET to the server which sends back a JSON object with the return information. I know how to decode the JSON once my php script has received it, but how would I go about actually getting it?
EDIT: Note - I send the server an HTTP GET, and it generates and sends back a JSON file. It is not a file sitting on the server.
Check out file_get_contents
$json = file_get_contents('http://somesite.com/getjson.php');
Browsers act differently based on what the server responds. It does not matter what type of request you make to the server (be it GET, POST, etc), but to return JSON as a response you have to set the header in the script you make the request to:
header('Content-Type: application/json;charset=utf-8;');
And then echo the JSON string, for example:
//...populating your result data array here...//
// Print out the JSON formatted data
echo json_encode($myData);
User agent will then get the JSON string. If AJAX made the request then you can simply parse that result into a JavaScript object that you can handle, like this:
//...AJAX request here...//
// Parse result to JavaScript object
var myData=JSON.parse(XMLHttp.responseText);
The header itself is not -really- necessary, but is sort-of good practice. JSON.parse() can parse the response regardless.

Categories