I've done this many times before with various SAAS services, but I can't parse the supposedly JSON responses I'm getting from Blitline image processing's API.
Here's what I do to handle the POST:
$body=#file_get_contents('php://input');
print_r($body);
results=%7B%22original_meta%22%3A%7B%22width
OR
$body=rawurldecode($body);
print_r($body);
results={"original_meta":{"width ...
When I go to print $body->original_meta->width, I get an empty string. You'll realize I didn't json_decode() the $body but that's because that returns an empty string too.
Removing the results= with substr($body, 8) doesn't help either.
Can anyone help?
Expanding on my comment: the POST data is standard x-www-form-urlencoded data so there's no need to access the raw POST data. You can simply access the $_POST array that contains the URL decoded data:
$data = json_decode($_POST['results']);
echo $data->original_meta->width;
Ok this is pretty ugly but it works...
$body = file_get_contents('php://input');
$body=rawurldecode($body);
$body=substr($body, 8);
$body=json_decode($body);
echo $body->original_meta->width; //1936
Related
I need to use a customer's API for loading JSON which only contains something like:
{"html" : "foo"}
The API is being used from other services so I'm pretty sure it's valid.
However, when trying to decode it using json_decode i'm always getting an empty string which means it's not valid. I found out i need to "fix" the JSON-String by replacing:
$json = str_replace("\\>", "\\\\>", $json); // \> = invalid json
It works mainly on each request but not on certain others but it's very tricky to debug and i can't imagine that replacing is the proper method.
How would i do it the easy way for converting the json string into a valid one?
thanks
Ok i could find out what's wrong:
The HTML contains backslashes in the closing tags, for example <br\>
You need to replace them like this:
$json = str_replace("\\>", "\\\\>", $json);
and json_decode will work
I am using a astrology API which sends an json string as response to the query. But i have been trying for long to convert it into json and retrieve different items from the response string. Here is the example of the response:
{"ashtakoota":{"status":true,"received_points":26},"manglik":{"status":true,"male_percentage":13.25,"female_percentage":13.75},"rajju_dosha":{"status":false},"vedha_dosha":{"status":false},"conclusion":{"match_report":"Marriage between the prospective bride and groom is highly recommended. The couple would have a long-lasting relationship, which would be filled with happiness and affluence."}}
I am using php script so i tried the following code :
$json = json_decode($res1, true);
TRY 1 --> echo array_values($json[1]);
TRY 2 --> echo $json.ashtakoota.status;
TRY 3 --> echo $res1.ashtakoota.status;
But the output is always blank. I doubt that $json is empty or the json response is not perfectly json.
PHP uses string keys for its arrays, which is what json_decode(...) returns. As such, you need to access them as:
echo $json['ashtakoota']['status'];
Which should then output true for your example JSON input.
The true parameter on json_decode will cause it to return an array, not an object. Your syntax for objects is also incorrect, it's not a dot, but rather -> that you need.
$json = json_decode($res1);
echo $json->ashtakoota->status;
I am facing error while getting response from JSON array.
here is PHP code I try this code.
var_dump($_POST);die;
empty
$data = (array) json_decode($HTTP_RAW_POST_DATA, true);
var_dump($data);
empty
$arJson =(array) json_decode( $_POST, true );
var_dump($arJson);
this one also empty here is postman results.
Try this:
$postData = json_decode(file_get_contents("php://input"));
If you simply POST a good old HTML form, the request looks something like this:
POST /page.php HTTP/1.1
key1=value1&key2=value2&key3=value3
But if you are working with Ajax a lot, this probaby also includes exchanging more complex data with types (string, int, bool) and structures (arrays, objects), so in most cases JSON is the best choice. But a request with a JSON-payload would look something like this:
POST /page.php HTTP/1.1
{"key1":"value1","key2":"value2","key3":"value3"}
The content would now be application/json (or at least none of the above mentioned), so PHP's $_POST-wrapper doesn't know how to handle that (yet).
The data is still there, you just can't access it through the wrapper. So you need to fetch it yourself in raw format with file_get_contents('php://input') (as long as it's not multipart/form-data-encoded).
If your whole POST body contains the JSON, you can get it using thid piece of code:
$json = file_get_contents('php://input');
$decoded = json_decode($json);
You can get value like this:
$str = file_get_content("php://input");
$data = json_decode($str,true);
Hope you can help.
I'm trying to read data from a decompiled application of Android with a php server. I used wireshark to understand what types of data the application sends, and the result is:
{"initType":"first time","parameters":true,"details":................}
I trying to capture this data and insert them in a file with this php code:
<?php
$json = $_POST["initType"];
$decoded = json_decode($json, TRUE);
if ($decoded === FALSE) {
throw new Exception('Bad JSON format.');
}
$file_handle = fopen('tmp.json', 'w');
fwrite($file_handle, $decoded);
fclose($file_handle);
?>
The file is correctly generated but it's empty. What is the error?
Because $decoded is an array, use a loop to write it to file or write the encoded JSON to file ($json). Try using this:
fwrite('tmp.json', print_r($decoded, TRUE));
or:
file_put_contents('tmp.json', print_r($decoded, TRUE));
Update (per your comments):
If you run a print_r($decoded) and it prints nothing, there is a problem with the decoding process of the JSON object passed in. I would recommend checking this to make sure it is formatted correctly. JSON formatting is a strict business and will halt your end goal if you are missing a double-quote or bracket. Start by echoing out $json ($_POST["initType"]) and compare the format to examples posted online (just Google "json formatting"). I can tell you that one thing that stands out to me is: "parameters":true (from your example above). I have a strong suspicion that the key true should be in double quotes. If you are positive that the JSON variable is correct syntactically, I don't think I would be of any more help. Using json_decode() to produce an array to very straight forward once you get it right.
Don't decode the json at all -this only brings the problem of trying to serialize an array that burmat mentioned in his answer.
Write to the file the json content straight away:
fwrite($file_handle, $json);
Also, though I am not PHP expert it seems you access the body of the post request wrongly. Please refer to the following post.
I want to pass a JSON: {"name":"jason","age":"20} in PHP though POST
In RoR, I can get the two values by using params["name"] & params["age"]
But I don't know how to get them in PHP.
I understand that I can 'translate' the JSON string into associative array by using json_decode but I don't know how to get the JSON string.
In my PHP code, I has tried something like this:
<?php
$json_string = $_POST['params'];
$json_object= json_decode($json_string);
print_r($json_object);
echo $json_object->name;
echo " ";
echo $json_object->age;
?>
Then I has tested the PHP with terminal and I got the correct result
curl -d 'params={"name":"jason", "age":"20"}' xxxx/test_json_decode.php
It works but it seems strange to me, because I didn't set the 'Content-Type: application/json'
Is it the correct way to parse JSON in PHP?
The content-type is only useful in certain cases, such as jquery doing a standard .post where you haven't explicitly told it to expect a json response. A json string is just text, and the content-type is just a clue to the receiver. but you could still send a json string with image/jpeg and still decode it and get a native structure again.
As long as what you pass into json_decode() is a valid JSON string, regardless of the mime-type it was sent with, it'll be decoded into a native structure.