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;
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
Hello! The data in table is like that, and I cannot echo these entries individually. I want to show this data in HTML table like for example, Subject: Math, Correct: 34, Wrong: 6.
I am new in php, please help me with this case.
The data in the table seems to be in JSON format. You can convert it to a PHP object using json_decode() then print that object using print_r().
When put all together, you get
echo print_r(json_decode($data), true);
Note, I have to edit this response back to what it is now because #fenil-shah had changed it some something else that was not suitable. Please send your own response instead of making others say what they didn't intend to.
#fenil-shah, my answer was written the way it was on purpose. Here are the explanations:
In general, if you want to stay in control of the result of the print_r() function, you need to return its result as a string. That's why I have passed true as second parameter for the print_r() function. You wouldn't using print_r() without returning its result as a string in a middle of another script because it will output some text in an uncontrolled manner that can break an add. Once you have the return string, you can send it to a log file or do whatever you want with it.
json_decode works beautifully without passing it a true as second parameter. The OP's example is showing a object. You edit was purposely changing the decoded object to an array with associative array. Why?
You have removed the space after the comma which you had moved in from the print_r() to the json_decode() to make it look like json_decode($data,true). You need to know that the space was there for two reasons: Readability and Compliance with the PSR-2 standard (read more about that PHP coding standard at https://www.php-fig.org/psr/psr-2/#46-method-and-function-calls).
There are echo "",print_r() and print() function available in php to print data.If query is returning array then use print_r() function but if query is not returning anything or invalid fetch method in php then data is not getting display by any of these functions.
I think this is what you want as a output.
You can decode the JSON received from database using json_decode() function and get your result transformed in associative array.
Later on passing the array in foreach() loop will do your work accordingly
<?php
$result = '{
"30": {
"subject_id":343,
"correct_answers":34,
"wrong _answers":61,
"not_answered":0,
"time_spent":3801,
"time_to_spend":3680,
"time_spent_correct_ answers":3286,
"time_spent_wrong_answers":515
},
"52": {
"subject_id":52,
"correct_answers":7,
"wrong_answers":3,
"not_answered":0,
"time_spent":883 ,
"time_to_spend":94343,
"time_spent_correct_ans wers":352,
"time_spent wrong_answers":441
},
"53": {
"subject_id":53,
"correct_answers":3,
"wrong_answers":7,
"not_answered":43,
"time_spent":584 ,
"time_to_spend":900,
"time_spent_correct_ans wers":154,
"time_spent wrong_answers":430
}
}';
$json_decoded_data = json_decode($result,true);
?>
<table>
<tbody>
<tr>
<th>subject_id</th>
<th>correct_answers</th>
<th>wrong_answers</th>
</tr>
<?php
foreach($json_decoded_data as $row){
echo "<tr>";
echo "<td>".$row['subject_id']."</td>";
echo "<td>".$row['correct_answers']."</td>";
echo "<td>".$row['correct_answers']."</td>";
echo "</tr>";
}
?>
</tbody>
</table>
I can send json from android to php but i'm unable to extract the data from json object in php. Can anyone help me to that in php?
I tried json_decode($json) to decode the json data.
What I was doing is I'm sending json object from android in get method and receiving the data in php side like this..
<?php
$json=$_GET['data'];
$d_json=json_decode($json) or json_decode($json,true);
?>
but when I was trying to access "$d_json['meal'][0]['name]" or
"$d_json->meal[0]->name" it was showing illegal index.
First I would try to print the $d_json to the screen - to see what is the value it holds.
If $d_json is not empty, but it is not an array (but a string) I would try a little bit of formatting:
$d_json = json_decode( stripslashes( $json ), true );
Then print_r (or var_dump, var_export) the result to see whether it returns an array.
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.
I am running a Debian box with PHP v5.2.17. I am trying to get around the cross-domain issue with an XML file and am using this got to fetch any xml and return json:
<?php
header('content-type: application/json; charset=utf-8');
if( strlen($_GET["feed"]) >= 13 ) {
$xml = file_get_contents(urldecode($_GET["feed"]));
if($xml) {
$data = #simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($data);
echo isset($_GET["callback"]) ? "{$_GET[’callback’]}($json)" : $json;
}
}
?>
The problem is, its not returning valid json to jquery.. The start character is "(" and the end is ")" where jquery wants "[" as the start and "]" as the end. I've taken the output and used several online validation tools to check it..
Is there a way I can change these characters prior to sending back or pass json_encode options?
You could change json_encode($data) to json_encode(array($data)) if it expects an array (like you're saying):
$json = json_encode(array($data));
EDIT: Also, I believe the SimpleXml call will result in a bunch of SimpleXmlElements, perhaps json_encode then thinks it should be objects, instead of arrays? Perhaps casting to an array will yield the correct results.
You cannot json_encode() SimpleXMLElements (that's the type that is returned by simplexml_load_string(). You have to convert the data from the XML file into some native PHP type (most likely an array).
SORRY that's wrong. json_encode() can in fact encode SimpleXMLElements (at least on my PHP version 5.3.4). So if your client-side code expects an array you must wrap your $data in an array:
$json = json_encode(array($data));
We can use json_encode() function most probably on array. so you first take XML content into PHP array and then apply json_encode().I think this will solve your problem..
It seems that you are sending an empty callback parameter or something, but the callback parameter in jQuery must look exactly like this: callback=?