file_get_contents returns an empty string - php

I am sending this json to my php site (http://example.com/webhook/) as a post from a third-party site, but all I get is an empty array.
{
"listing_id": 0,
"guest_id": 0,
"confirmation_code": "confirmation code",
"start_date": "2015-05-05",
"nights": 1,
"number_of_guests": 3,
"listing_base_price": 399
}
And for this, I am using the following server-side code in the index.php file:
$json = file_get_contents('php://input');
echo $json;
$data = json_decode($json, True);
The response is expected to be json so I am unable to use var_dump() hence it returns other than json.

Related

json_decode returns null and bool false

I have code:
<?php $json = '[{"title":" \\ud83c\\uddf7\\ud83c\\uddfa \\u0420\\u043e\\u0441\\u0441\\u0438\\u0439\\u0441\\u043a\\u043e\\u0435 \\u043a\\u0430\\u0437\\u0438\\u043d\\u043e #1
\\ud83c\\uddf7\\ud83c\\uddfa ","desc":"\\u0422\\u043e\\u043b\\u044c\\u043a\\u043e
\\u0437\\u0430\\u0440\\u0435\\u0433\\u0438\\u0441\\u0442\\u0440\\u0438\\u0440\\u0443\\u0439\\u0441\\u044f \\u0438 \\u0438\\u0433\\u0440\\u0430\\u0439
\\u043f\\u0435\\u0440\\u0432\\u044b\\u0439 \\u0440\\u0430\\u0437 \\u0437\\u0430 \\u043d\\u0430\\u0448
\\u0441\\u0447\\u0451\\u0442","icn":"https://1.mbvnclick1.com/ic?sid=2&data=0eikgji0Ck2EKXJkLTJfLie%2FKy%2FvWYZiVPrhxIOQsl6VkyioGiy%2B4DYdpqaaMXlM5dVPkQoRzngoPAlvQ3w1pREOxlMjuR7DQHq6Yz0oA7ZXT9CV1ut2ICfrquV9FoQ%2BjltIeJAcUnB%2BTMvTjn%2BGs1lvh5bOIUUXYa0tIJCe%2BJe2LX38OpOLAJ%2B7U1h12rvXozelMT5SGd67wzUnFI7er3gJycSu7WAH72sUTT%2FZ%2F3nJQOZBOMHY8WyX8jqel5Mo8BMNLzIXHyjpA%2BiZlgYsEg%3D%3D","img":"https://1.mbvnclick1.com/im?sid=2&data=ZQqgvmU6z8ZR4RPBdAhPWcdkbt5b%2BWp435ln18YHYo1SXskUGSiZhGwhvcXnWECjuteCzRQRWIhfYTUDd4wLcUq7jKaYn55gJUbQZr3UM6SAx2dKKXUVQVmstTsIdXma7gZ57%2B8L58uusM7pf8HpgSTreH8rjJIX%2BQEruq544CQQF%2FTNxTpCAesrBgQpkUOL76hSB%2F0Eaw3yYO0mDUDR6zKLXkDo6cxruIRrER05RSFJVtlFr3ihmDZHJQZnl%2FO6","url":"https://1.mbvnclick1.com/clpsh?sid=2&d=1&data=h3OP98W8RXI52WXh0xUpzzPCqkn%2Boc1q7OZh2tb7pLxLU4il0MNlbTTRR%2FQJ3Ryj98kKbM2eOgq%2FVtMBpmy4huEGwavyp41rQdZTT%2Fjdsu0QcYNMwUiNBH4mifSNaIzMTDYTeB9hZ8BPwGw%2F171wk2af2qmrmLi7e13XtfK%2BFpZltozDNAqS%2BDJkvH3SVKJHo8TkGjb2FQonQoXeVXqfp6jp2MYLqp%2FOFf6dOcERVM%2Ff%2FYBgEZ2E%2FpzuMZSywxPt49sveDcfOE%2F9LOjBu6%2BU1XymVQdknq%2B0MzuJAd6Eq8%2FH4q%2F%2B7dlgvivqQm30C%2FvhG%2FfGSYQPEY%2BHdzAJZ%2FStRjZmMtGhsqHbMkGENTil4bzlo8VvMW6H2yLPpVVw8Eqw86jXlndl7qPusmT4W4VUVQzMEnKgDbiJFPGy45vE%2B3QOCqafNoCq90X7U%2FLlvr9Gxdox8qAUyhAMbqJU5p0GYlMk6iJDD3GaG%2FqAZN5hzM0%3D","price":"0.0055"}]';
$json = json_decode($json, true); var_dump($json);
echo '<br>';
echo json_last_error();
?>
It returns null and if I check JSON for errors it returns bool(false). What is wrong? Online decoders are decoding json normally. JSON is advertisment I'm using for test.
I've been searching for issue for hours. I've deleted urls from json, checking if another jsons are working on site (they work). IDK what to do
$json = preg_replace('/[[:cntrl:]]/', '', $json); $array = json_decode($json, true);
I should preg_replace before decoding JSON

Php json _decode function returns null on long data

I pull data from a json file on the remote server. This json file has 97000 Lines of json code. It returns null when I decode the Json file. When I debug the Json errors, I see that there is no error.
Json file : https://opendata.ecdc.europa.eu/covid19/casedistribution/json/
$json = file_get_contents("https://opendata.ecdc.europa.eu/covid19/casedistribution/json/");
$json = json_decode($json, true);
var_dump($json); // Return Null
But when I decode another json file there is no error
$json = file_get_contents("https://randomuser.me/api/");
$json = json_decode($json, true);
var_dump($json); // Return Array
Could this be due to the size of the data?
Thanks for advance
The file starts with a BOM, which is a syntax error for json_decode.
Ultimately this should be fixed by the host, as a workaround you can strip the first three bytes:
if (substr($json, 0, 3) == "\xEF\xBB\xBF") {
$json = substr($json, 3);
}

Unable to get json_decode() output

I am trying to decode a simple json string POSTed to a php file.
<?php
$jsonData = file_get_contents('php://input');
$data_back = json_decode($jsonData, true);
echo $jsonData;
echo $data_back;
?>
I tested this by POSTing this sample JSON
{"sensorid": SS0023, "x": 475, "y":212} with application/json Content-Type.
But it is returning the $jsonData values only. json_decode isn't doing anything and returning null.
Help ?
your json format must be like this
{"sensorid": "SS0023", "x": "475", "y":"212"}

Pulling data from weird JSON array response

I am working with an API and the response comes back weird. I need to grab the ID field from the response below.
{
"message_campaigns": [
{
"embedded_errors": [],
"id": "2729",
"is_legacy_message": false,
"is_setup_complete": false,
"message_campaign_type_id": 1,
"name": "Message Campaign 1",
"organization_id": 123
}
]
}
Below is my attempt:
$result = curl_exec($ch);
curl_close($ch); // Seems like good practice
$responseData = json_decode($result, TRUE);
print_r($responseData);
I have tried several methods and cannot get it to work
$responseData[0]['id'];
$responseData->id;
I can't figure out how to get the id to display.
Assuming your curl_exec actually returns a response because you've set curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
If I look at your json response you need:
$responseData['message_campaigns'][0]['id'];
It's because the result is an array, as you pass the second parameter as true to json_decode:
When TRUE, returned objects will be converted into associative arrays.
In JSON, {} stands for objects, and [] stands for array. You've converted all objects to associative arrays, so this'll work:
$responseData['message_campaigns'][0]['id']
You have the second parameter of json_decode set to true, so an array (not an object) will be returned.
You'll also need to access message_campaigns as the first item in the array.
$responseData['message_campaigns'][0]['id'];
This can be tested:
$result = <<< EOT
{
"message_campaigns": [
{
"embedded_errors": [],
"id": "2729",
"is_legacy_message": false,
"is_setup_complete": false,
"message_campaign_type_id": 1,
"name": "Message Campaign 1",
"organization_id": 123
}
]
}
EOT;
$responseData = json_decode($result, TRUE);
echo $responseData['message_campaigns'][0]['id'];
// 2729

GET info from external API/URL using PHP

I have the URL http://api.minetools.eu/ping/play.desnia.net/25565 which outputs statistics of my server.
For example:
{
"description": "A Minecraft Server",
"favicon": null,
"latency": 64.646,
"players": {
"max": 20,
"online": 0,
"sample": []
},
"version": {
"name": "Spigot 1.8.8",
"protocol": 47
}
}
I want to get the value of online player count to display it on my website as: Online Players: online amount
Can anyone help?
I tried to do:
<b> Online players:
<?php
$content = file_get_contents("http://api.minetools.eu/ping/play.desnia.net/25565");
echo ($content, ["online"]);
}
?>
</b>
But it didn't work.
1) Don't use file_get_contents() (If you can help it)
This is because you'd need to enable fopen_wrappers to enable file_get_contents() to work on an external source. Sometimes this is closed (depending on your host; like shared hosting), so your application will break.
Generally a good alternative is curl()
2) Using curl() to perform a GET request
This is pretty straight forward. Issue a GET request with some headers using curl().
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://api.minetools.eu/ping/play.desnia.net/25565",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
3) Using the response
The response comes back in a JSON object. We can use json_decode() to put this into a usable object or array.
$response = json_decode($response, true); //because of true, it's in an array
echo 'Online: '. $response['players']['online'];
Your server is returning a JSON string.
So you should use json_decode() function to convert that into a plain PHP object.
Thereafter you can access any variable of that object.
So, something like this shall help
<?php
$content = file_get_contents("http://api.minetools.eu/ping/play.desnia.net/25565");
$result = json_decode($content);
print_r( $result->players->online );
?>
More details for json_decode can be read here -
http://php.net/manual/en/function.json-decode.php
Your webservice (URL: http://api.minetools.eu/ping/play.desnia.net/25565) returns JSON.
This is a standard format, and PHP (at least since 5.2) supports decoding it natively - you'll get some form of PHP structure back from it.
Your code currently doesn't work (your syntax is meaningless on the echo - and even if it was valid, you're treating a string copy of the raw JSON data as an array - which won't work), you need to have PHP interpret (decode) the JSON data first:
http://php.net/manual/en/function.json-decode.php
<?php
$statisticsJson = file_get_contents("http://api.minetools.eu/ping/play.desnia.net/25565");
$statisticsObj = json_decode($statisticsJson);
Your $statisticsObj will be NULL if an error occurred - and you can get that error using other standard PHP functions:
http://php.net/manual/en/function.json-last-error.php
Assuming it isn't NULL, you can examine the structure of the object with var_dump($statisticsObj) - and then alter your code to print it out appropriately.
In short, something like:
<?php
$statisticsJson = file_get_contents("http://api.minetools.eu/ping/play.desnia.net/25565");
$statisticsObj = json_decode($statisticsJson);
if ($statisticsObj !== null) {
echo $statisticsObj->players->online;
} else {
echo "Unknown";
}
You should also check what comes back from file_get_contents() too - various return values can come back (which would blow up json_decode()) on errors. See the documentation for possibilities:
http://php.net/manual/en/function.file-get-contents.php
I'd also wrap the entire thing in a function or class method to keep your code tidy. A simple "almost complete" solution could look like this:
<?php
function getServerStatistics($url) {
$statisticsJson = file_get_contents($url);
if ($statisticsJson === false) {
return false;
}
$statisticsObj = json_decode($statisticsJson);
if ($statisticsObj !== null) {
return false;
}
return $statisticsObj;
}
// ...
$stats = getServerStatistics($url);
if ($stats !== false) {
print $stats->players->online;
}
If you want better handling over server / HTTP errors etc, I'd look at using curl_*() - http://php.net/manual/en/book.curl.php
Ideally you also should be confirming the structure returned from your webservice is what you expected before blindly making assumptions too. You can do that with something like property_exists().
Happy hacking!
Since it's returning an array you should use print_r or var_dump instead of echo. Or perhaps it threw you an error.

Categories