MySQL > JSON, Causing errors with URL's - php

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.

Related

Having trouble with json who have image url

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.

Ampersands in database

I am trying to write a php function that goes to my database and pulls a list of URLS and arranges them into an xml structure and creates an xml file.
Problem is, Some of these urls will contain an ampersand that ARE HTML encoded. So, the database is good, but currently, when my function tries to grab these URLS, the script will stop at the ampersands and not finish.
One example link from database:
http://www.mysite.com/myfile.php?select=on&league_id=8&sport=15
function buildXML($con) {
//build xml file
$sql = "SELECT * FROM url_links";
$res = mysql_query($sql,$con);
$gameArray = array ();
while ($row = mysql_fetch_array($res))
{
array_push($row['form_link']);
}
$xml = '<?xml version="1.0" encoding="utf-8"?><channel>';
foreach ($gameArray as $link)
{
$xml .= "<item><link>".$link."</link></item>";
}
$xml .= '</channel>';
file_put_contents('../xml/full_rankings.xml',$xml);
}
mysql_close($con);
session_write_close();
If i need to alter the links in the database, that can be done.
You can use PHP's html_entity_decode() on the $link to convert & back to &.
In your XML, you could also wrap the link in <![CDATA[]]> to allow it to contain the characters.
$xml .= "<item><link><![CDATA[" . html_entity_decode($link) . "]]></link></item>";
UPDATE
Just noticed you're actually not putting anything into the $gameArray:
array_push($row['form_link']);
Try:
$gameArray[] = $row['form_link'];
* #Musa looks to have noticed it first, for due credit.
Look at this line
array_push($row['form_link']);
you never put anything in the $gameArray array, it should be
array_push($gameArray, $row['form_link']);
You need to use htmlspecialchars_decode. It will decode any encoded special characters in string passed to it.
This is most likely what you are looking for:
http://www.php.net/manual/en/function.mysql-real-escape-string.php
Read the documentation, there are examples at the bottom of the page...
'&' in oracleSQL and MySQL are used in queries as a logical operator which is why it is tossing an error.
You may also want to decode the HTML...

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;

simplexml_load_file with & (ampersand) in url with Solr

I am using Solr and have the following query which works fine from my browser:
http://www.someipaddress.com:8983/solr/select?q=*&fq=shopid:40&start=0&rows=18&fq=manufacturer:"Bausch+%26+Lomb"
In part of the return xml I see:
<str>manufacturer:"Bausch & Lomb"</str>
However when I try and get the above url using simplexml_load_file like this:
$xml = simplexml_load_file("http://127.0.0.1:8983/solr/select?q=*&fq=shopid:40&start=0&rows=18&fq=manufacturer:\"Bausch+%26+Lomb\"");
I get no results because Solr is being passed the manufacturer string that looks like this (from print_r):
[str] => Array ( [0] => shopid:40 [1] => manufacturer:"Bausch+%26+Lomb" )
So when I am doing the query through the browser I pass in %26 but it deals with it correctly in the query. But when I use simplexml_load_file it remains as %26 and so the query fails.
Try:
simplexml_load_file(rawurlencode('http://127.0.0.1:8983/solr/select?q=*&fq=shopid:40&start=0&rows=18&fq=manufacturer:"Bausch' .urlencode('&'). 'Lomb"'))
See note on file parameter: http://php.net/manual/en/function.simplexml-load-file.php
Didn't work:
$url = 'http://127.0.0.1:8983/solr/select?q=*&fq=shopid:40&start=0&rows=18';
$url .= '&fq=manufacturer:"Bausch' .urlencode('&'). 'Lomb"';
simplexml_load_file(rawurlencode($url));
Manufacturer part of query came out as: "Bausch&Lomb";
Didn't work:
simplexml_load_file(rawurlencode('http://127.0.0.1:8983/solr/select?q=*&fq=shopid:40&start=0&rows=18&fq=manufacturer:"Bausch ' .urlencode('&'). ' Lomb"'))
Adding spaces next to the words Bausch and Lomb produced simplexml_load file error.
Worked:
simplexml_load_file(rawurlencode('http://127.0.0.1:8983/solr/select?q=*&fq=shopid:40&start=0&rows=18&fq=manufacturer:"Bausch+' .urlencode('&'). '+Lomb"'))
Swapping spaces for + works!
This is how I ended up doing it dynamically.
$manufacturer = urlencode("Bausch & Lomb");
$manufacturer_insert = "&fq=manufacturer:\"$manufacturer\"";
$xml = simplexml_load_file(rawurlencode("http://127.0.0.1:8983/solr/select?q=$shopid_insert$start_insert$rows_insert$sort_insert$manufacturer_insert"));
That works for manufacturers with an ampersand in their name.
It is important to note that if you were passing values with spaces they will now need to be urlencoded before being added. For example:
Before I could just use this for my sort insert:
$sort_insert = "&sort=price desc";
Now I need to urlencode just "price desc". When I tried to urlencode the whole sort_insert string the simplexml query would fail.
After (works):
$sort = urlencode("price desc");
$sort_insert = "&sort=$sort";
Thanks again... Back to the project!

JSON character encoding in php script

I am retrieving json from a php file that connects to the database and then creates the json to be imported into my page via an ajax call.
Some of the database columns have file paths in them, ie images/myfolder/myfile
The json that I see when I open the page in a web browser formats the file path like this:
\/images\/myfolder\/myfile
Are the escaped characters going to break the json?
i.e, if i do var icon_image = myData.file
will icon_image hold: \/images\/myfolder\/myfile or /images/myfolder/myfile
I am hoping the second option from above, but if it doesn't how do I get it to display as /images/myfolder/myfile
I have put mb_internal_encoding( 'UTF-8' ); at the top of the php page
The script that generates the json is as follows:
mb_internal_encoding( 'UTF-8' );
mysql_select_db($database_growth_conn, $growth_conn);
$query_rs_icons = sprintf("SELECT * FROM icons_ico ORDER BY name_ico");
//echo($query_rs_icons);
$rs_icons = mysql_query($query_rs_icons, $growth_conn) or die(mysql_error());
$row_rs_icons = mysql_fetch_assoc($rs_icons);
$totalRows_rs_icons = mysql_num_rows($rs_icons)
$rows = array();
while($r = mysql_fetch_assoc($rs_icons)) {
$rows[] = $r;
}
$jsondata = json_encode($rows);
echo '{"icons":'.$jsondata.'}';
are the escaped characters going to break the json?
No. A backslash-escaped non-special punctuation is just the same as the punctuation itself. The JS string literals "a/b" and "a\/b" result in the same string value, a/b.
json_encode escapes the forward slash character for you so that if you try to include a string with the sequence </script> in it in a script element, it doesn't prematurely end the script block.

Categories