Having trouble with json who have image url - php

I tried to make json file to convert my data from database to json and ended up with error (SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data)
when i use a database which not containt img_url it could work but when there is img_url always error.
i tried using .php extension and it works but the img_url is a mess but when i use .json extension it shows the error
this is my code:
$stmt = $conn->prepare("SELECT namajurusan, fakultas, deskripsi, img_url FROM tbl_prodi;");
//executing the query
$stmt->execute();
//binding results to the query
$stmt->bind_result($namajurusan, $fakultas, $deskripsi, $img_url);
$prodi = array();
//traversing through all the result
while($stmt->fetch()){
$temp = array();
$temp['namajurusan'] = $namajurusan;
$temp['fakultas'] = $fakultas;
$temp['deskripsi'] = $deskripsi;
$temp['img_url'] = $img_url;
array_push($prodi, $temp);
}
//displaying the result in json format
echo json_encode($prodi);

Make sure you are not sending unparsed strings to your JSON before calling json_encode.
Try to see it using var_dump().

Encode the url using urlencode before adding it to the json.
PHP Docs: http://php.net/manual/en/function.urlencode.php
Update:
Instead of using array_push($prodi, $temp); use $prodi[] = $temp.

Related

BLOB field returns null JSON

I am saving my images directly in the database (Yes I have read about that and know it's better to save the path to the image).
The problem is selecting the image field which is a blob returns NULLto my JSON. I have alot read quite a few stackoverflow links of the same query but still not a clear explanation/ answer received has been able to help me.
I have encoded using base_64 but when doing so nothing is showed on the webpage.
Would appreciate if I could be pointed in the correct direction.
This is part of my code:
header("Content-Type:application/json");
//select query
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
if (!empty($rows))
{
$encode = array("StudentsList" => $rows);
//$json_response=json_encode($encode);
$json_response=base64_encode($encode);
echo $json_response;
echo json_last_error(); //Returns 0
}
if you need the json data
please use json_encode
example
echo json_encode($json_response);
and also read php manual
http://php.net/manual/en/function.json-encode.php

PHP: How to json encode of hindi language in response

I am working with a translation API but here is an issue. I am using JSON in response and when I do json_encode of Hindi then the out is like "\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948"
My code is given below
$data = array();
$data['hindi'] = 'यह कार है';
$data['english'] = 'This is car';
echo json_encode($data); die;
and the response is
{"hindi":"\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948","english":"This is car"}
If you are running PHP 5.4 or greater, pass the JSON_UNESCAPED_UNICODEparameter when calling json_encode
Example:
$data = array();
$data['hindi'] = 'यह कार है';
$data['english'] = 'This is car';
echo json_encode($data, JSON_UNESCAPED_UNICODE);
die;
This is correct json and when you display it in the browser and / or parse it, it will result in an object with the correct keys and values:
var json_string = '{"hindi":"\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948","english":"This is car"}',
json = JSON.parse(json_string);
// or directly:
var json2 = {"hindi":"\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948","english":"This is car"};
console.log(json_string);
console.log(json);
console.log(json2);
document.write(json_string);
document.write('<br>');
document.write(json.hindi);
document.write('<br>');
document.write(json2.hindi);
The reason for this is likely that these characters are not in UTF-8 (I could not find them, at least). From the PHP documentation on json_encode:
All string data must be UTF-8 encoded.
This means that it will have to convert it to a 'description' of the characters. Do not worry, if you decode it again it will very likely be correct.
I have a solution to this problem. It works fine for me.
$data = array();
$data['hindi'] = base64_encode('यह कार है');
$data['english'] = 'This is car';
$encoded_text=json_encode($data);
To retrieve the hindi part of data:
$hindi=base64_decode(json_decode($encoded_text)->hindi);

PHP + json encode + Datatables

I'm using a jquery plugin called DataTables, and it requires me to return a json string in order to render the table.
Currently, the outputted json looks like this (see the aaData array):
{"sEcho":0,"aaData":[[{"ID":"1","idPatient":"122342","idFacility":"3","idTreatment":"3"}]]}
I'm wondering if the { } braces should actually be in the aaData array. In fact, I think the braces are actually what's causing the JSON parse error.
The actual code that generates this is listed below. (core->dbh is a PDO handle)
<?php
require_once('core/Core.php');
$core = Core::get_instance();
$sql = 'SELECT ID, idPatient, idFacility, idTreatment
FROM Pathology WHERE idPatient = 122342';
$stmt = $core->dbh->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
// bind parameters
$stmt->execute();
// prepare output for DataTables
$data = array("sEcho" =>intval($_GET['sEcho']),
"aaData" =>array()
);
while($result = $stmt->fetchAll()) {
$data['aaData'][] = $result;
}
echo json_encode($data);
?>
Could someone please tell me how can I remove the curly braces, or if the JSON is improperly formatted in another way that could be causing the parse error?
Thanks
The JSON is fine. You are encoding it with PHP via json_encode, that can't be the problem. My guess would be that by doing this $data['aaData'][] = $result; you are nesting twice (see the double brackets) your results and the plugin fails. Try this: $data['aaData'] = $result;

json_decode(json_encode(an indexed array)) gives NULL

i encode the user entred testarea content with json_encode
here is how it storred in mysql (there is a return to line after "aaa")
{"content":"aaa
bbb"}
now when i get the the content from database and trying to decoded it using json_decode, i get NULL for this, instead of what expected.
what wrrong? a bug in PHP?
EDIT 1: more details
$data =array('content'=>$textareaText);
$addres_insert = "INSERT INTO `rtable` (`data`) VALUES ('".json_encode($data)."');";
$rows = mysql_query($addres_insert);
then to get the content
$query = "SELECT * FROM `rtable` WHERE id = '".$id."'";
$rows = mysql_query($query);
if ( $rows ){
$row = mysql_fetch_array($rows);
$res['data'] = json_decode($row['data']);//i tryed substr($row['data'],3) but didn't work
}
JavaScript and JSON do not allow line returns to be contained within a string. You need to escape them.
json_encode() should escape them automatically for you.
Here is the output of my playing with your JSON code supplied on the PHP interactive shell:
php > $json = '{"content":"aaa
php ' bbb"}';
php > var_dump(json_decode($json, true));
NULL
As you can see when I escape your line return it works just fine:
php > $json = '{"content":"aaa\n bbb"}';
php > var_dump(json_decode($json, true));
array(1) {
["content"]=>
string(8) "aaa
bbb"
}
This is also further discussed in a previous question relating to a similar problem: Problem when retrieving text in JSON format containing line breaks with jQuery

MySQL > JSON, Causing errors with URL's

I have this code converting a mysql query to json:
$sth = mysql_query('SELECT * FROM `staff` ORDER BY `id` DESC LIMIT 20') or die(mysql_error());
$rows = array();
while($r = mysql_fetch_array($sth)) {
$rows[] = $r;
}
print json_encode($rows);
Works great, but i have in my database, a url field, here is a sample json row:
{"0":"4","id":"4","1":"Noter 2","name":"Noter 2","2":null,"desc":null,"3":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","iconurl":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","4":"1262032317","date":"1262032317","5":"dBelement, LLC","company":"dBelement, LLC","6":"http:\/\/dbelement.com\/","companyurl":"http:\/\/dbelement.com\/","7":"http:\/\/noter2.dbelement.com","appurl":"http:\/\/noter2.dbelement.com"},
How can i get around this?
I suppose the "problem" is the presence of backslashed in the URLs ?
Like :
http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg
Well, that's not a problem for Javascript : try to assign your JSON data to a Javascript object, and display one of those URL :
var data = {"0":"4","id":"4","1":"Noter 2","name":"Noter 2","2":null,"desc":null,"3":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","iconurl":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","4":"1262032317","date":"1262032317","5":"dBelement, LLC","company":"dBelement, LLC","6":"http:\/\/dbelement.com\/","companyurl":"http:\/\/dbelement.com\/","7":"http:\/\/noter2.dbelement.com","appurl":"http:\/\/noter2.dbelement.com"};
alert(data[3]);
The URL is displayed correctly :
http://images.apple.com/webapps/productivity/images/noter2_20091223182720-thumb.jpg
So, the backslashes are not a "problem" ;-)
And, in fact, if you take a look at the "string" section of json.org, you'll see that slashes have to be backslashed for your string to be valid.
I don't see a problem here. If you're wondering why the URLs look like this:
http:\/\/www.example.com\/
Instead of like this:
http://www.example.com/
It's because the / characters are being appropriately escaped. When you unserialize the JSON object in javascript, the URLs will look as they do in your database.

Categories