How to parse JSON passing in PHP web service - php

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.

Related

php: json_decode containing HTML fails to decode

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

how to solve json decode returns null error

My API URL Returned code in browser as shown below. but json_decode($api_url,true); returns null.
i checked json_last_error();, it returns 4(json error syntax).
it worked with json_decode(file_get_contents($api_url),true);
why it isn't work with json_decode. please help
{"dataset":{"id":27153572,"dataset_code":"20MICRONS_A_DEBT","database_code":"DEB","name":"20 Microns Limited,Total Debt","description":"\u003cp\u003e20 Microns Limited(NSE:20MICRONS)-Total Debt(Annual)\u003c/p\u003e","refreshed_at":"2018-09-21T08:04:08.278Z","newest_available_date":"2018-03-31","oldest_available_date":"2005-03-31","column_names":["PERIOD","STANDALONE","CONSOLIDATED"],"frequency":"annual","type":"Time Series","premium":true,"limit":null,"transform":null,"column_index":null,"start_date":"2005-03-31","end_date":"2018-03-31","data":[["2018-03-31",128.56,133.68],["2017-03-31",144.9,151.73],["2016-03-31",155.18,163.41],["2015-03-31",152.8,164.62],["2014-03-31",162.01,176.64],["2013-03-31",148.49,164.73],["2012-03-31",144.67,158.6],["2011-03-31",81.42,120.31],["2010-03-31",84.35,87.35],["2009-03-31",58.62,58.62],["2008-03-31",46.52,null],["2007-03-31",42.46,null],["2006-03-31",40.03,null],["2005-03-31",38.98,null]],"collapse":null,"order":null,"database_id":14992}}
What you are trying to do has no sense. $api_url is just an url so when you try to decode it then it doesn't have a json stucture and it will throw an exeption.
What you should decode is the data that this url returns to you.
So First you should get data from url then use json_decode($api_url,true);.
To get data you can use file_get_contents or curl.
Props to u_mulder who hit the nail on the head but I want to break this down for you a little.
Purpose of file_get_contents():
The file_get_contents() function is an inbuilt function in PHP which is used to read the contents of a file into a string.
Please note that the 'file' can be a file residing on your web server or a remote file (URL), which in essence will give you a web document back.
Purpose of json_decode():
The json_decode() function is an inbuilt function in PHP which is used to decode a JSON string. It converts a JSON encoded string into a PHP variable.
With that in mind you can see that performing json_decode on an invalid JSON string or a URL will render your result as NULL.
json_decode('https://www.website.com')
This is essentially what you are doing. performing the file_get_contents inside your json_decode first converts your URL/File ('https://www.website.com') into a string, that string then having JSON is then converted into an array by json_decode.

Get json string elements

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;

Send xml string in json object using php slim

I have written a REST Api using slim framework 3, and returning response in JSON like this,
return $response->withHeader(
'Content-type',
'application/json; charset=utf-8'
)->withJson($data, 200);
which is working fine.
$xml = '<?xml version="1.0" encoding="UTF-8"?><dialog createdBy=""createDate=""><dialog>' // looks like this
$data = [
'name' => 'xmlName',
'xml' => $xml // fetching from db
]
Now, I have xml string stored in database and want to send it to the client end, I have to save that xml string as in another database as it is.
But when I encode xml string, my json gets break.
I have also tried like,
json_encode($data, JSON_HEX_TAG);
which converts my xml to.
"\u003C?xml version=\"1.0\" encoding=\"UTF-8\"?\u003E\n\u003Cdialog createdBy=\"\"
How can I correctly encode the xml in JSON and then get back the original xml string as it is?
Your feedback is much appreciated.
If you look at the withJson() source code you'll see that all it does with data is processing it with json_encode()—nothing special on the Slim side. In fact, your XML is just fine: \u003C and \u003E are the entities for < and >. Remember that JSON is a data format for computers, not people!
Additionally, the JSON spec states that you need to have a top level object or array. So you can't just send a string back to the client and expect it to be processed as JSON because it will not be JSON. If json_encode() does not just crash it's because it has been designed to encode partial JSON since it's a useful feature some times. You absolutely need to design a valid JSON structure, e.g.:
->withJson(array($xml), 200)
Actually I just found my answer by the hint of htmlentities #Álvaro González gave.
I just converted my xml string like,
[
'name' => 'xmlName',
'xml' => htmlentities($xml)
]
I am able to receive the xml string as it is without any json break.

Parsing JSON POST PHP, unable to generate object

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

Categories