JSON encode output with symbol "\/" with PHP - php

I new in PHP programming and I try to make simple API with simple PHP. Below my snippet code :
$con = mysqli_connect(HOST, USER, PASS, DB);
$sql_results = mysqli_query($con, "SELECT * FROM `table-images`");
$rows = array();
while($r = mysqli_fetch_assoc($sql_results)) {
$rows[] = $r;
}
echo'{"response":'.json_encode($rows).'}';
The code above have JSON output like below :
{"response":[{"id":"31","shirtImage":"Content\/Images\/Short Sleeve\/874be7b82812f76c944d71706c9651eb.gif"},{"id":"32","shirtImage":"Content\/Images\/Short Sleeve\/b-Cleaned.png"}]}
I want to know why value of field shirtImage have extra symbol \ . In my database the value is correct example Content/Images/Short Sleeve/b-Cleaned.png but when it encode to JSON the output have changed. How to fix this?
I find some keyword regarding my case, but it still does not work.

There is nothing to fix.
JSON is a format that encodes a data structure in a way that makes it storable and transportable. When the data is needed for processing you have to decode it from JSON.
You can use json_decode() in PHP or JSON.parse() in JavaScript to restore the original data and work with it.
Many other languages provide a function or library to work with JSON.
You should not generate JSON manually. The correct way to produce a JSON from your data is:
$response = ['response' => $rows];
echo json_encode($response);
Because the values stored in $rows are arrays (and because it is easier to work with arrays in PHP than with bare objects) when you decode the JSON in PHP it's recommended to pass true as the second argument to json_decode(). This way it uses arrays in the restored data structure.
Otherwise it produces instances of stdClass which are bare PHP objects. The arrays are more versatile.

json_encode() escapes forward slash. Try using:
echo'{"response":'.json_encode($rows, JSON_UNESCAPED_SLASHES).'}';

Its due to escaping / with `\` and it will be removed when you decode your json back.
Try to decode it back.
$d = json_decode('{"response":[{"id":"31","shirtImage":"Content/Images/Short Sleeve/874be7b82812f76c944d71706c9651eb.gif"},{"id":"32","shirtImage":"Content/Images/Short Sleeve/b-Cleaned.png"}]}');
print_r($d);die; // This will give you the original data with out `\`

Related

Best way to json encode an array that has a json encoded value already? PHP

I have an array with multiple items in it one of which is an already encoded json string. I'm wanting to json encode the whole array but in doing so it re-json_encodes the json and adds slashes to it. The only way I've found to fix this is to json_decode the value and then encode the whole array. I feel like this is a waste of resources though and I feel like there has to be a better way. Is doing it that way the best possible way?
Here's a sample of the array I'm trying to json_encode.
$arr = array();
$arr["var1"] = '{"test":"test"}';
$arr["var2"] = 'foo';
$arr["var3"] = 'bar';
If I don't decode the var1 first and I just encode the whole array I get a result like so
{"var1":"{\"test\":\"test\"}","var2":"foo","var3":"bar"}
Notice the slashes in the json object.
json_encode() returns a string containing the json representation of a value.
In the example, a php string is passed as one element of the array '{"test":"test"}', thus json_encode() is encoding it appropriately into json format, with escaped quotes "{\"test\":\"test\"}".
If decoding nested json is a very resource heavy task, a workaround is to use a placeholder instead of the value, {"var1":"PLACEHOLDER","var2":"foo","var3":"bar"}, and then using str_replace() to replace it.
However, simply decoding it as you described is probably a cleaner solution, if its not resource heavy.

PHP and JSON datatype in MySQL

Despite of recent implementation of JSON datatype to MySQL I can't find any word on it in the related PHP documentation.
My question is: will PHP automatically convert cells of JSON column to the actual values - arrays or literals - or will it provide just json-encoded strings. Like:
$sql_query = "SELECT JSON_ARRAY(1,2,3)";
$result = mysqli_query($sql_query);
$value = mysqli_fetch_row($result)[0];
// what is a $value? Array(1,2,3) or a string "[1,2,3]"
// do I have to use json_decode() to get an actual array here?
(Don't have MySQL 5.7 at hand right now, so can't check it myself.)
i think with serialize and unserialize you get whatever you want.
so just store all values using serialize and you can get that values with unserialize.
so just check serialize and unserialize.

PHP Unserialize data for use in array - sub standard characters in string

I am using a jQuery plugin of nestable forms and storing the order of these in a database using serialize (achieved through JS). Once I retrieve this data from the database I need to be able to unserialize it so that each piece of data can be used.
An example of the data serialized and stored is
[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]
The number of ID's stored in each serialized data varies and the JS plugin adds the [ and ] brackets around the serialization.
I have used http://www.unserialize.com/ to test an unserialization of the data and it proves successful using print_r. I have tried replicating this with the following code:
<?php
print_r(unserialize('[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]'));
?>
but I get an error. I am guessing that I need to use something similar to strip_tags to remove the brackets, but am unsure. The error given is as follows
Notice: unserialize(): Error at offset 0 of 70 bytes
Once I have the unserialized data I need to be able to use each ID as a variable and I am assuming to do so I need to do something as:
<?php
$array = unserialize('[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]');
foreach($array as $key => $val)
{
// Do something here, use each individial ID however
// e.g database insert using $val['id']; to get H592736029375 then K235098273598 and finally B039571208517
}
?>
Is anyone able to offer any help as to how to strip the serialized data correctly to have the ID's ready in an array to then be used in the foreach function?
Much appreciated.
PHP's serialize() and unserialize() functions are PHP specific, not for communicating with other languages.
It looks like your JS serialize function is actually generating JSON though, so on the PHP side, use json_decode() rather than unserialize.
Here's a fiddle
$data = '[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]';
$array = json_decode($data, true);
foreach($array as $index=>$data){
echo "$index) {$data['id']}\n";
}
Outputs:
0) H592736029375
1) K235098273598
2) B039571208517

send an Array from Android to PHP Script over HTTP and get the data

I would like to send an integer array with 30 values Integer[] temp = new Integer[30] over HTTP (POST) to PHP an get the data in PHP again. How can I do that? I know how to send a single value, like a string, but not how to send an array.
One way is to serialize the array in the way the php serialize command does it.
After receiving the string value(by the method you currently use), you can use the unserialize command to get the array in your php code.
Here is a litle php example to demonstrate the workflow.
$arr = array(1,2,3,4,5,6);
$stringArr = serialize($arr);
echo $stringArr;
echo "<br/>";
$arr2 = unserialize($stringArr);
if ($arr === $arr2)
{
echo "arrays are equal";
}
The output of the script is:
a:6:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;}
arrays are equal
The main difficulty is to construct the resulting string for complex structures (in your case, it is pretty straight forward for an array of integers).
This fact results in the second approach.
One can use a serialization API or another notation than used by the php example.
As stated by the others, JSON is one of the widespread notations.
PHP also provides a possibility to serialize and unserialize json objects.
Simply use json_decode and look at the example in the manual.

Data stored in json

I have my data stored in a JSON string like these...
a:1:{s:15:"s2member_level1";s:1:"1";}
How can i read this values in mysql?
I need to know if the value "s2member_level1" is 1.
Thanks!!!
That's not JSON but a string resulted from calling serialize() in PHP. You cannot parse it easily in MySQL. If you can use PHP, use the unserialize function:
$obj = unserialize($data_from_mysql);
if ($obj['s2member_level1'] == 1) {
// more code here
}
You can convert data to JSON in PHP using the json_encode function. In a similar way, you construct an object from a JSON string using json_decode.
#Lekensteyn is correct, but you could do a like statement, although its performance would most likely be very poor. My true answer is to change how you store this information to take advantages of best performing queries.
select * from table
where column like '%s:15:"s2member_level1";s:1:"1";%';
#Lekensteyn is right about the type of this particular String, but for others, PHP has json_decode which you can use to convert a JSON object to a PHP object. It would be considerably more difficult to read such an object using MySQL only.
This is no json, but serialized data. It was probably serialized with the 'serialize' function of PHP. Try:
print_r(unserialize('a:1:{s:15:"s2member_level1";s:1:"1";}'));
... to unserialize it.

Categories