I have a symfony app that uses the json_encode and json_decode to keep a record of some prices.
The problem is that json_decode works OK in one file (I can decode the string stored in my PSQL database), but when I call it from other file json_decode returns null, I've check the file encodings (all are utf-8) the tables and database encoding(utf-8 too). So I don't know where the problem can be, tried utf8_encode() too...
Any help will be appreciated.
Thanks.
Here's the valid encoded json (It was an array encoded by php json_encode)
{"1":{"1":{"fechaInicio":"30-05-2011","precios":{"1":{"precio":"20000","abreviatura":"CLP"}},"fechaRetiro":"31-05-2011"}},"2":{"2":{"fechaInicio":"30-05-2011","precios":{"1":{"precio":"20000","abreviatura":"CLP"}},"fechaRetiro":"31-05-2011"}}}
The array:
$preciosOfertor = Array ( [unidades] => Array ( [1] => Array ( [1] => Array ( [fechaInicio] => 30-05-2011 [precios] => Array ( [1] => Array ( [precio] => 20000 [abreviatura] => CLP ) ) [fechaRetiro] => 31-05-2011 ) ) [2] => Array ( [2] => Array ( [fechaInicio] => 30-05-2011 [precios] => Array ( [1] => Array ( [precio] => 20000 [abreviatura] => CLP ) ) [fechaRetiro] => 31-05-2011 ) ) ) )
To encode it I use:
$preciosOfertor = json_encode($preciosOfertor);
Then I call
$precios = json_decode($databaseObject->getPreciosOfertor(),true);
When i use json_decode in the file that encodes the array it works, but then when I use it in other file of the project I just get NULL with var_dump().
Installed Services_JSON as suggested, but now I'm getting an empty array
The encoded json with Services_JSON is this one:
{"unidades":{"1":{"1":{"fechaInicio":"30-05-2011","precios":{"1":{"precio":"20000","abreviatura":"CLP"}},"fechaRetiro":"31-05-2011"}}}}
But when I call $json->decode() I get Array ( )
Ok people, first thank you all for the help.
I got the solution and It was all thanks to Zend Json library.
Symfony uses escaping strategies to prevent XSS attacks, SQL Injection attacks, etc. So what happened here in my case, when I called json_encode and json_decode it was inside the object that Doctrine generates to represent my object (In this case a reservation), so because it was a local call to the row data (valoresOfertor), the data from the database was not escaped thus the methods worked fine.
But then, when I tried to encode and decode the values of the row outside the reservation class, Symfony used it's escaping strategy so
"
became
"
So, trying different JSON libraries, I used Zend one, and saw the exception that displayed (Syntax Error:
at Zend_Json::decode('{"unidades":{"1":{"1":{"fechaInicio":"30-05-2011","precios":{"1":{"precio":"20000","abreviatura":"CLP"}},"fechaRetiro":"31-05-2011"}},"2":{"2":{"fechaInicio":"30-05-2011","precios":{"1":{"precio":"20000","abreviatura":"CLP"}},"fechaRetiro":"31-05-2011"}}}}')
in SF_ROOT_DIR/apps/saas/modules/editreserva/templates/habitacionesSuccess.php line 20 ...
So then i Added the following line:
htmlspecialchars_decode($jsonVariable);
And it worked.
I hope it helps someone if he experiments the same with symfony and json.
As far as I know, there were one or more bugs in json_encode() and json_encode() in previous versions of PHP. You could try to update PHP to the latest version or you could use an external library to encode and decode JSON. There are some, but I think PEAR JSON is the best.
it might be the UTF-8 BOM present. Try using UTF without BOM encoding. Also echo the json_last_error() to see what's the problem.
EDIT:
It IS a valid JSON
From php.net : NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
So either you've set e recursion limit lower than the data depth (which may not seem to be the case, if you say that it does work on another page), or the json cannot be decoded.
If it works on one page and it doesn't in another, check the file encoding.
The first page may be encoded to utf-8 (the encoding of your json) but the second one might be something else (like ascii). check the bom also.Youw may need to encode the page to utf-8 without bom.
If it's a template you're dealing it, have a look at:
$sf_data->getRaw();
http://www.geeganage.com/symfony-json-made-easy/
Related
My code
I have a function get_points_table() that returns an array like so:
Array
(
[0] => Array
(
[player] => steve
[points] => 10
)
[1] => Array
(
[player] => jess
[points] => 7
)
)
I would like to pass this array as JSON to a JavaScript script to output as HTML.
My current script looks like this:
<?php
require_once 'db.php';
$points_table = get_points_table($dbh);
echo json_encode($points_table);
?>
My problem
My understanding is that if I don't sanitise the data before echo'ing it back, there is a security risk posed by a player setting their username to something like steve<script>alert()</script> or using some other combinations of special characters.
My research suggests I need to use some combination of htmlentities() and/or htmlspecialchars() to safely output the data. However htmlentities() does not return utf8 encoded data, so I also need to use utf8_encode() in order for json_encode() to understand it. htmlentities() also does not allow you to pass an array as a value.
What I've tried
I've tried various combinations of array_walk(), array_walk_recursive() and array_map() to apply htmlentities() to each value of my array but to no success. I've also tried accessing the values in nested foreach loops to no success either. e.g.:
foreach($points_table as $key=>value) {
htmlspecialchars($value);
htmlentities($value);
utf8_encode($value);
}
echo json_encode($points_table);
What I need
I would like to know how to sanitise my array so I can safely pass it as JSON to be output as HTML, even if the user sets their username to something like steve<script>alert()</script><php echo "hello world";?> ;-- - &%00
Ideally I would like to do this so that the end result has the username in human readable format without converting symbols to html entities (i.e. steve<script> not steve"<script>")
This feels like a very common thing developers would do and should have a simple and easy answer, but I have done much searching and cannot work it out for myself.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Create array printed with print_r
Duplicate of How create an array from the output of an array printed with print_r?
which also has a nice code example to solve this
I need to reverse an error log which has as output print_r($data,true).
Example data would look like:
Array
(
[subject] => this is the subject
[body] => <p>Dear user,</p><p>this is the body of the email</p>
[from_id] => 0
[from_email] => admin#karakas.org
[to] => Array
(
[0] => Array
(
[id] => 0
[email] => 64909
)
)
[send_to_inbox] => 1
)
In the PHP manual there's a print_r_reverse() function in comments :
http://php.net/manual/en/function.print-r.php
However var_export() can be an alternative if your logs are generated using var_export(). This way, you only need eval() to retrieve the exported array.
The output of print_r() is not designed to parsed; it's designed to be read by a developer for debugging purposes. You should not be trying to parse it.
If you really must parse a PHP data dump of this nature, the var_export() function is intended for this kind of thing. However, I wouldn't recommend parsing this either -- it's still unlikely to be the best solution for you.
If your intention is to store a string representation of an array structure, and then parse it later, you would be better off using either the serialize()/unserialize() functions, or the json_encode()/json_decode() functions.
Both of these will give you a much more reliable and easily parseable data dump format. Of the two, I'd recommend json_encode() every time, as not only is it easy to work with, it's also supported by other languages, easy to read manually, and compact.
In short, don't parse print_r() output; use json_encode()/json_decode() instead.
http://uk1.php.net/manual/en/function.json-encode.php
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Create array printed with print_r
Duplicate of How create an array from the output of an array printed with print_r?
which also has a nice code example to solve this
I need to reverse an error log which has as output print_r($data,true).
Example data would look like:
Array
(
[subject] => this is the subject
[body] => <p>Dear user,</p><p>this is the body of the email</p>
[from_id] => 0
[from_email] => admin#karakas.org
[to] => Array
(
[0] => Array
(
[id] => 0
[email] => 64909
)
)
[send_to_inbox] => 1
)
In the PHP manual there's a print_r_reverse() function in comments :
http://php.net/manual/en/function.print-r.php
However var_export() can be an alternative if your logs are generated using var_export(). This way, you only need eval() to retrieve the exported array.
The output of print_r() is not designed to parsed; it's designed to be read by a developer for debugging purposes. You should not be trying to parse it.
If you really must parse a PHP data dump of this nature, the var_export() function is intended for this kind of thing. However, I wouldn't recommend parsing this either -- it's still unlikely to be the best solution for you.
If your intention is to store a string representation of an array structure, and then parse it later, you would be better off using either the serialize()/unserialize() functions, or the json_encode()/json_decode() functions.
Both of these will give you a much more reliable and easily parseable data dump format. Of the two, I'd recommend json_encode() every time, as not only is it easy to work with, it's also supported by other languages, easy to read manually, and compact.
In short, don't parse print_r() output; use json_encode()/json_decode() instead.
http://uk1.php.net/manual/en/function.json-encode.php
I have a script that puts some cyrillic text into session variables like this: $_SESSION['cyrillic'][$y] where $y is an iterator, so in the end the array will look like this:
[cyrillic] => Array
(
[0] => ������
[1] => ��������
[2] => ������
[3] => ������
However, after struggling with UTF-8 headers in both PHP, HTML and files save charsets (with and without BOM), I've found out there is nothing wrong with the charset settings (apparently), as setting any other session variable with the cyrillic text in WILL WORK.
This means:$_SESSION['cyr']['txt'] = $cyrillic_string_here; will work just fine, as shown here:
[cyr] => Array
(
[txt] => десять
)
So, what I fail to understand then, is WHY can't I insert cyrillic into an array using a numeric key, but an alphabetical one? And how can I work around this when I -need- to use an iterating loop?
EDIT: It's not that. I can insert the same text into another variable and echo it, or a session variable without numeric key values and it will work fine.
EDIT: I also found this:
*The hard-to-find documentation sentence I'm about is: "The keys in the $_SESSION associative array are subject to the same limitations as regular variable names in PHP."*
But I thought I could make an array with a numeric value like this: $array[$i]? Or does it mean since the key is ASSOC that $array['text'][$i] wouldn't work?
Found the solution. I had a trim(strtolower($text)); wrapped around my cyrillic.
strtolower:
[These functions] only work when translation is between common characters in ISO 8859-1 and UTF-8, that means they will work well with western languages but not cyrillic or asian.
Thanks for your help.
I'm trying to call to a specific part of an array with the key # and it's not working. I can output the array and see it...
Array
(
[6] => Array
(
[0] => user#domain.com
[1] => user#domain.com
)
[7] => Array
(
[0] => user#domain.com
[1] => user#domain.com
)
[8] => Array
(
[0] => user#domain.com
[1] => user#domain.com
)
)
This array is $emailDB. I can call to the array manually with $emailDB[7] and it works, but if my call is dynamic like this it won't work...
<?php
$value = 7;
print_r($emailDB[$value]);
?>
I've never had an issue like this with an array so it's very odd. What really sucks is I'm under deadline with a form not working on a client's site...joy.
We tried this with no luck...
<?php
$value = 7;
print_r($emailDB[intval($value)]);
?>
I thought intval() would assist but it did not.
You're post implies a bug in php itself, which I highly doubt. What's more likely is that what you posted doesn't properly represent the code you're running.
Why don't try this. Make a brand new empty php file. Hardcode the array keys and values and assign them to the $emailDB variable, and then try
$value = 7;
print_r($emailDB[$value]);
You will see you don't have the problem that you claim. You have now started the debugging process, and now you can look at the working, and non working code to compare the difference.
Well, you are echoing an Array, which I assume is printing "Array" onto your screen. If you want to echo the actual contents of the array, you need to use print_r($array) or echo print_r($array, true). You can also try putting the value in quotes, like $emailDB["{$value}"] to see if that works, I sometimes have troubles with integers not going into things properly.
I agree with you all. It had to have been something whacky with how we were pulling in the data somehow. It was a tab-separated file we were exploding. I just re-wrote the whole thing entirely and imported the data into MySQL and all was well.
In hindsight, I have a sneaking suspicion it was a trim() command that was needed and likely nothing more. Dang it...too late, but I learned something about checking over the code for those types of things.