recently i used some JSON data in JQuery. now i want the same thing in PHP.
For Example:
MySQL query returns data like
$result='{"username":"john","age":"18", "birthdate":"19880221"}';
but when i echo this data in PHP, like:
echo $result.username;
echo $result.age;
it shows output:
{"username":"john","age":"18", "birthdate":"19880221"}.username
{"username":"john","age":"18", "birthdate":"19880221"}.age
but i want output this:
John
18
PHP is not Javascript, the . operator is for string concatenation and PHP has no native support for JSON syntax. You need to convert the JSON formatted data into an array and use array syntax:
$result = json_decode($result, true);
echo $result['username'];
echo $result['age'];
php is not js. you have to decode data first, using json_decode
if $result really contains the data you posted
Your result is actually just a string, formated like JSON. It's not an array in PHP. If U want to handle JSON output, you can use json_decode() first, and then get access to data via PHP array syntax like this:
$result = json_decode($result,true);
echo $result['some_key'];
Related
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 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 send a QueryString formatted text like bellow to a php Script via Ajax:
title=hello&custLength=200&custWidth=300
And I want to convert this text to a JSON Object by this result in PHP:
{
"title" : "hello",
"custLength" : 200,
"custWidth" : 300
}
How can i do that. Does anyone have a solution?
Edit :
In fact i have three element in a form by title , custLength and custWidth names and i tried to send these elements via serialize() jquery method as one parameter to PHP script.
this code is for Send data to php:
customizingOptions = $('#title,#custLength,#custWidth').serialize();
$.post('cardOperations',{action:'add','p_id':p_id,'quantity':quantity,'customizingOptions':customizingOptions},function(data){
if (data.success){
goBackBtn('show');
updateTopCard('new');
}
},'json');
in PHP script i used json_encode() for convert only customizingOptions parameter to a json.
But the result was not what I expected and result was a simple Text like this:
"title=hello&custLength=200&custWidth=300"
I realize this is old, but I've found the most concise and effective solution to be the following (assuming you can't just encode the $_GET global):
parse_str('title=hello&custLength=200&custWidth=300', $parsed);
echo json_encode($parsed);
Should work for any PHP version >= 5.2.0 (when json_encode() was introduced).
$check = "title=hello&custLength=200&custWidth=300";
$keywords = preg_split("/[\s,=,&]+/", $check);
$arr=array();
for($i=0;$i<sizeof($keywords);$i++)
{
$arr[$keywords[$i]] = $keywords[++$i];
}
$obj =(object)$arr;
echo json_encode($obj);
Try This code You Get Your Desired Result
The easiest way how to achiev JSON object from $_GET string is really simple:
json_encode($_GET)
this will produce the following json output:
{"title":"hello","custLength":"200","custWidth":"300"}
Or you can use some parse function as first (for example - save all variables into array) and then you can send the parsed output into json_encode() function.
Without specifying detailed requirements, there are many solutions.
I am trying to decode json with PHP but dont know where am i wrong. Here is my code
$rr ='var modelsGlobal = [{"value":"FAFW3801LW","productdetailurl":"/Washers-Dryers/Washers/Front-Load/FAFW3801LW/"}{"value":"FAFW3801LW","productdetailurl":"/Washers-Dryers/Washers/Front-Load/FAFW3801LW/"}]';
$json = json_decode($rr, true);
foreach($json['modelsGlobal'] as $json){
$prod_id = $json["value"];
}
Please help
You are trying to decode (broken) JavaScript, not JSON.
JSON wouldn't include var modelsGlobal = and array members need a , between them.
Run your data through a linter.
After you fix the errors which are preventing the parsing, the JSON doesn't start with an object with a modelsGlobal, so loop over the array in $json directly.
Your JSON is incorrect. It is not JSON but JavaScript and it lacks a comma to separate the two objects of the array.
If you use PHP 5.3+ use json_last_error to check errors with json_encode/json_decode.
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=?