invalid json response in php when json response inside json response - json

i have try to print json response but "" are added to my json response
i tried below code php and id generated by drupal field
<?php
$data = array("title"=>"test","body"=>"test body");
$php = json_encode($data,JSON_FORCE_OBJECT);
echo json_encode(array("php"=>$php,"id"=>10));
?>
output :
{"php":"{\"title\":\"test\",\"body\":\"test body\"}","id":10}
but i want output like below
{"php":{"title":"test","body":"test body"},"id":10}
i added some more code for above problem
{"php":"{\"title\":\"test\",\"body\":\"test body\"}","id":10}
why not remove json_encode from echo json_encode($php);
how i can get above output` second time

You're encoding in JSON two times :
$data = array("title"=>"test","body"=>"test body");
$php = json_encode($data,JSON_FORCE_OBJECT);
echo $php ; // remove json_encode() here
After question edit:
$data = array("title"=>"test","body"=>"test body");
echo json_encode(array("php"=>$data,"id"=>10));

You can also simply do this,
<?php
$data = array("title"=>"test","body"=>"test body");
echo json_encode(array("php"=>$data,"id"=>10));
?>

Related

Load API Json data in table

I am an old Greek Pharmacist and my hobby is web development.
So, I have this url
https://clinicaltrials.gov/api/query/study_fields?expr=lansoprazole&fields=NCTId%2CBriefTitle%2CCondition&min_rnk=1&max_rnk=10&fmt=json
and I want to have all its Json data in an html table.
I tried with Fetch Api, but I did not succeed :(
How can this be done with JavaScript or PHP?
Thank you in advance!
<?php
$jsondump = file_get_contents('https://clinicaltrials.gov/api/query/study_fields?expr=lansoprazole&fields=NCTId%2CBriefTitle%2CCondition&min_rnk=1&max_rnk=50&fmt=json');
// Decode JSON data to PHP associative array
$data = json_decode($jsondump, true);
if($data['StudyFieldsResponse']['MaxRank'] <= $data['StudyFieldsResponse']['NStudiesFound'])
{
$keynum=$data['StudyFieldsResponse']['MaxRank'];
}
else
{
$keynum=$data['StudyFieldsResponse']['NStudiesFound'];
}
echo ("NStudiesReturned: ") . $keynum;
echo "<hr><br>";
?>
<table border=1 width=800>
<tr><td>Rank</td><td>NCTId</td><td>BriefTitle</td><td>Condition</td></tr>
<?php
$x=0;
while ($x <= $keynum-1){
$rank = $data['StudyFieldsResponse']['StudyFields'][$x]['Rank'];
$nctid=$data['StudyFieldsResponse']['StudyFields'][$x]['NCTId'][0];
$title = $data['StudyFieldsResponse']['StudyFields'][$x]['BriefTitle'][0];
$condition_count=count($data['StudyFieldsResponse']['StudyFields'][$x]['Condition']);
//echo $condition_count;
echo "<tr><td> $rank</td><td>$nctid</td><td>$title</td><td><b>";
$ccx=0;
while ($ccx <= $condition_count-1){
$condition = $data['StudyFieldsResponse']['StudyFields'][$x]['Condition'][$ccx];
echo "<p>$condition</p>";
$ccx++;
}
echo "</b></td></tr>";
$x++;
}
?>
</table>

string element of array is not able to access after json decode

this is my code for decode array
$transfer = '{"type": "BALANCE","status": "REJECTED"}'; $json = json_decode($transfer); echo $json->status;
it is not displaying status value.
if I change status to integer value.
$transfer = '{"type": "BALANCE","status": "1234"}';
then it is displaying status value as 1234.
how to display status value if its in string format.
This is working fine
<?php
$transfer = '{"type": "BALANCE","status": "REJECTED"}';
$json = json_decode($transfer);
echo $json->status; //displays REJECTED
?>

Retrieve particular field from serialized data

Suppose I have following data :
a:1:{s:4:"date";a:3:{s:2:"mm";s:2:"12";s:2:"dd";s:2:"06";s:2:"yy";s:4:"1991";}}
I want the value of mm and dd from that serialized string.
I have following query to retrieve above data :
$birthday = "select meta_key, meta_value from $wpdb->usermeta where meta_key='pie_date_5'";
$user_birthday = $wpdb->get_results($birthday);
foreach($user_birthday as $ubday){
$ubd = $ubday->meta_value; echo $ubd;
echo json_decode($ubd[0]->mm);
}
I am not able to do that simple thing. Please help me out.
You have to use unserialize instead of json_decode because it's a serialized string.
So you could try something like this:
$user_birthday = 'a:1:{s:4:"date";a:3:{s:2:"mm";s:2:"12";s:2:"dd";s:2:"06";s:2:"yy";s:4:"1991";}}'; //the serialized string you get from your query
$upday = unserialize( $user_birthday );
echo $upday['date']['mm'] . PHP_EOL;
echo $upday['date']['dd'];
EDIT: If you want to read all properties from the $upday array you could use a foreach-loop
foreach ( $upday['date'] as $key => $value ) :
echo $key . ' = ' . $value . PHP_EOL;
endforeach;

return an element from array of json output

I am trying to extract specific values returned from google api
<?php
$url='http://maps.googleapis.com/maps/api/distancematrix/json?origins=19.1629924,72.83930190&destinations=19.1802370,72.8554149&sensor=false';
$contents = file_get_contents($url);
$contents = utf8_encode($contents);
$array=json_decode($contents);
echo $array['rows']['elements']['distance']['value'];
?>
I expected the value of 4238 to be returned. Instead I get an error:
`PHP Fatal error: Cannot use object of type stdClass as array in test9.php on` line 7
Te correct solution is:
echo $array->rows[0]->elements[0]->distance->value;
Do the following to see the json:
<?php
$url='http://maps.googleapis.com/maps/api/distancematrix/json?origins=19.1629924,72.83930190&destinations=19.1802370,72.8554149&sensor=false';
$contents = file_get_contents($url);
$contents = utf8_encode($contents);
echo "<pre>";
echo $contents;
echo "\n";
echo "\n";
$array=json_decode($contents);
echo $array->rows[0]->elements[0]->distance->value;
?>
http://www.json.org/
have you tried node.js?
The following code solved the problem:
$array=json_decode($contents, true);
echo $array['rows'][0]['elements'][0]['distance']['value'];

MySQL to XML file

I am trying to get MySQL database into an xml file; here is my code:
<?php
header("Content-type: text/xml");
include 'dbc.php';
$query = "SELECT * FROM airports LIMIT 50";
$result = mysql_query($query, $link)
or die('Error querying database.');
$xml = new SimpleXMLElement('<xml/>');
while($row = mysql_fetch_assoc($result)) {
$draw = $xml->addChild('draw');
$draw->addChild('ident',htmlentities(iconv("UTF-8", "ISO-8859-1//IGNORE",$row['ident'])));
$draw->addChild('name',htmlentities(iconv("UTF-8", "ISO-8859-1//IGNORE",$row['name'])));
}
mysql_close($link);
$fp = fopen("links2.xml","wb");
fwrite($fp,$xml->asXML());
fclose($fp);
Here is the error Im getting:
XML Parsing Error: no element found
Location: /sql2xml2.php
Line Number 1, Column 2:
-^
What am I doing wrong???
Your XML is considered invalid in your XML reader because of the thrown warning, thus the XML Parsing Error: junk after document element issue.
As for the warning itself, you need to escape special entities (namely &, < and > in your content when adding it like that (using str_replace usually works well for only those 3 when it comes to XML, htmlentities may yield undesired effects, unless you supply PHP 5.4's ENT_XML1 mode).
Refer to a related answer for more information of why this happens.
If you want just to export MySQL database to local XML file you can use mysqldump tool:
mysqldump --xml -u username -p databasename [tablename] > filename.xml
Got it to work with this code:
<?
header("content-type:text/xml");
function getXML($query="SELECT * FROM airports limit 50")
{
include 'dbc.php';
$result = mysql_query($query, $link)
or die('Error querying database.');
$columns="";
echo "<xml>\n";
while($row=mysql_fetch_assoc($result))
{
$columns.="\t<airport>\n";
foreach($row as $key => $value)
{
$value = htmlentities(iconv("UTF-8", "ISO-8859-1//TRANSLIT",$value));
$value = htmlentities(iconv("UTF-8", "ISO-8859-1//IGNORE",$value));
$columns.="\t\t<$key>$value</$key>\n";
}
$columns.="\t</airport>\n";
}
echo $columns;
echo "</xml>\n";
}
getXML();
?>