Hardcode JSON Array in PHP - php

I have two variables from two different SQL queries that I want to put in to one JSON Array (i.e $hometown and $topcat). I am trying to hardcode it but not sure how it's suppose to look.
print(json_encode('{"hometown":"' . $hometown .'", "category":"'. $topcat .'"}'));
My output is this:
{\"hometown\":\"Seattle, WA\", \"category\":\"Movies\"}"
Not sure where the slashes are coming from (I suppose I can to do stripslashes?) and it seems I need to add '[' and ']' as well? What is the proper formatting for this?

json_encode() takes your array or object, it doesn't accept strings that are already JSON encoded. It can be done like this:
print json_encode(array('hometown' => $hometown, 'category' => $topcat));
Outputs
{"hometown":"Seattle, WA","category":"Movies"}

That string already looks like JSON; why are you trying to encode it again?
Not sure where the slashes are coming from
Because that code encodes a string that contains double-quotes, which must be escaped in JSON.
Unsafe, and dumb, but easy solution:
print('{"hometown":"' . $hometown .'", "category":"'. $topcat .'"}');
Better solution:
print(json_encode(array(
'hometown' => $hometown,
'category' => $topcat,
)));

The string is already formatted as a JSON object, encoding is what is adding the slashes. The json_encode() function is made to convert arrays to JSON objects not strings also whats with the print(), print() is deprecated and echo() should be used.
Here is your solution:
echo '{"hometown":"'.$hometown.'", "category":"'.$topcat.'"}';

Related

json_encode Returning a PHP Array

So I am working with PHP to pass a PHP array over a jQuery Ajax request to another PHP page. This is quite the task. For some reason, my json_encode is returning an array instead of a string, I am not quite sure why. Here is my PHP code:
$new_spreadsheet = nl2br($_POST['spreadsheet']);
$new_spreadsheet = explode('<br />', $new_spreadsheet);
array_shift($new_spreadsheet);
$new_spreadsheet = array_values($new_spreadsheet);
echo json_encode($new_spreadsheet);
I would show you the output, but it is really long. Basically this is outputting a PHP array which consists of each row on the spreadsheet. This is what I want to have, but the problem is that I don't want the quotes and everything in the array. I am pretty sure I need to run json_decode, but when I do that my code returns an error saying that the parameter needs to be a string. I can tell something is not right, but am not quite sure what I need to change. I would appreciate any advice.
Update: At this point, when I try to loop through the array and print each value, the first array index is equal to a double quote like so: ". There are double quotes in random values throughout the area. I am not quite sure about what is causing this.
If I echo the rows from within the json_encoded PHP array onto the console, I get the following output:
"
correct value
correct value
correct value
"
You're using JSON, which means you have to adhere to somewhat more stringent syntax rules than Javascript's. e.g.
<?php
$arr = array('This' => 'is', 'an' => 'array in php');
echo json_encode($array);
?>
output:
{"This":"is","an":"array in PHP"}
There is NO way to avoid getting quotes on the values, as they're a fundamental requirement of JSON (and Javascript). If you don't want quotes, then don't use JSON.
try only br.
$new_spreadsheet = explode("<br>", $new_spreadsheet);
It will work. and json_enode can never return an array. try var_dump and check.Also make sure before you post, use htmlspecialcharacters.

PHP Get method, escaping the "&" value

i have this Download link that will be using a GET method, here's my code:
echo "<a href='dlexcel.php?pname=".s1."&year=".s2."'>DOWNLOAD</a>";
that will be recieve by dlexcel.php
$_GET['pname'].$_GET['year'];
the problem is, s1 is string that can contain the a value &. and the string itself is not complete when $_GET is called.
i already used str_replace and preg_replace but i dont know how to. i need to pull the & out and replace it with something else, i just dont know how or what.
You need to use
urlencode($s1)
when encoding a string to be used in a query part of a URL
Try http_build_query(). http://www.php.net/http_build_query
echo '<a href="dlexcel.php?', http_build_query(array(
'pname' => $s1,
'year' => $s2
), '">DOWNLOAD</a>');
This takes care of encoding data, while building the entire query string from an array for you, meaning you aren't manually hacking it together. Remember, there is more than just & that you must encode.

build SQL statement from json encoded string php

Welcome Stackoverflow nation ! I'm trying to decode json encoded string into SQL statement withing php.
Lets say I've such a json encoded string =>
$j = '{"groupOp":"AND","rules":[{"field":"id","op":"cn","data":"A"},{"field":"i_name","op":"cn","data":"B"}]}';
I want to build SQL WHERE clause (needed for filterToolbar search in jqGrid), something like this => "WHERE id LIKE %A% AND i_name LIKE %B% " and etc.
I've done this =>
$d = json_decode($j);
$filterArray = get_object_vars($d); // makes array
foreach($filterArray as $m_arr_name => $m_arr_key){
// here I can't made up my mind how to continue build SQL statement which I've mentioned above
}
Any ideas how to do that , thanks preliminarily :)
The first problem is you will want to pull out the groupOp operator.
Then, you have an object and inside that you have an array of objects, so you may want to look at the results of filterArray as that won't have the value you want.
Then, when you loop through, you will want to do it with an index so you can just pull the values out in order.
You may want to look at this question to see how you can get data out of the array:
json decode in php
And here is another question that may be helpful for you:
How to decode a JSON String with several objects in PHP?
There is an answer with an implementation for the server-side php code here
Correction: I had to unescape double-quotes in the 'filters' parameter to get it working:
$filters = str_replace('\"','"' ,$_POST['filters']);

PHP http_build_query special symbols

I want to create an url out of an array with the help of http_build_query (PHP). This is the Array:
$a = array("skip" => 1, "limit" => 1, "startkey" => '["naturalProduct","Apple"]')
After calling
$s = http_build_query($a);
I get the following string $s:
skip=1&limit=1&startkey=%5B%22naturalProduct%22%2C%22Apple%22%5D
My problem is, that I would need an url like this:
skip=1&limit=1&startkey=["naturalProduct","Apple"]
which means, that I don't want to convert the following symbols: ",[]
I have written a conversion function which I call after the http_build_query:
str_replace(array("%5B", "%22", "%5D", "%2C"), array('[', '"', ']', ','), $uri);
My question now: Is there a better way to reach the expected results?
My question now: Is there a better way to reach the expected results?
Yes, there is something better. http_build_query­Docs by default uses an URL encoding as outlined in RFC 1738. You just want to de-urlencode the string. For that there is a function that does this in your case: urldecode­Docs:
$s = http_build_query($a);
echo urldecode($s);
I hope you are aware that your URL then is no longer a valid URL after you've done that. You already decoded it.
You don't need to decode the special characters - they are automatically decoded when PHP's $_GET superglobal is generated. When I do print_r($_GET) with your generated string, I get this:
Array ( [skip] => 1 [limit] => 1 [startkey] => [\"naturalProduct\",\"Apple\"] )
Which has decoded every character, but hasn't unescaped the double quotes. To unescape them, use stripslashes():
echo stripslashes($_GET['startkey']);
This gives
["naturalProduct","Apple"]
Which you can then parse or use however you wish. A better solution, as ThiefMaster mentions in the comments, is to disabled magic_quotes_gpc in your php.ini; it's deprecated and scheduled for removal completely in PHP6.

json_encode remove quotes from keys?

If I use json_encode() on an array like this:
return json_encode(array( 'foo' => 'bar'));
The return is:
{'foo' : 'bar'}
The key is passed as a literal, and that is tripping up my script. What I really need is:
{ foo : 'bar' }
Does json_encode do that or do I have to strip the quotes out myself with some ugly regex?
When I test this portion of code :
echo json_encode(array( 'foo' => 'bar'));
die;
I get :
{"foo":"bar"}
Which is valid JSON.
(Note these are double-quotes, and not simple-quotes as you posted)
The ouput you are asking for :
{ foo : 'bar' }
is valid Javascript, but is not valid JSON -- so json_encode will not return that.
See json.org for the specification of the JSON format -- which is a subset of Javascript, and not Javascript itself.
Instead of "stripping the quotes out myself with some ugly regex", you should adapt your code, so it accepts valid JSON : this is way better, in my opinion.
No, json_encode will not do this for you. The json specification specifcally requires that keys be quoted strings. This is done to ensure that keys which are javascript reserved words won't break the data object.
If you want to convert your JSON to print a javascript object (that was my case) you can use ugly regex like this:
$myJsonString = preg_replace('/"([^"]+)"\s*:\s*/', '$1:', $myJsonString);
Source: https://hdtuto.com/article/php-how-to-remove-double-quotes-from-json-array-keys
How is it tripping up your script?
And per the JSON specification, key names are supposed to be strings. The 2nd snippet you posted is not valid JSON.
Thanks, everyone. I did not know that about the JSON spec. The issue was in fact with my script because I had not set the datatype of my $.ajax() function to "json"
What I learned today -- JSON and Javascript are not the same thing!

Categories