How can I convert an array to a serialized string that I can write to a session file? This is being done in a command line script, not in a browser, so I can not use session_write_close().
I have tried serialize() function and that does not convert it properly (see below).
Notice: I already know I shouldn't manually write to a session file, and I should use the database for session data instead.
If I use file_get_contents() on the session file I get:
user_id|i:4;user_first_name|s:9:"FirstName";user_last_name|s:8:"LastName";user_last_login|s:10:"2016-06-03";random_data|a:4:{s:2:"ID";i:83;s:3:"URL";a:1:{i:0;s:23:"https://www.example.com";}s:4:"Date";s:10:"2016-06-08";s:4:"Year";s:4:"2016";}
I convert it to an array with some PHP and get:
Array
(
[user_id] => 1
[user_first_name] => FirstName
[user_last_name] => LastName
[user_last_login] => 2016-06-03
[random_data] => Array
(
[ID] => 83
[URL] => Array
(
[0] => https://www.example.com
)
[Date] => 2016-06-08
[Year] => 2016
)
)
Now I need to convert the array back into a string for the session file:
user_id|i:4;user_first_name|s:9:"FirstName";user_last_name|s:8:"LastName";user_last_login|s:10:"2016-06-03";random_data|a:4:{s:2:"ID";i:83;s:3:"URL";a:1:{i:0;s:23:"https://www.example.com";}s:4:"Date";s:10:"2016-06-08";s:4:"Year";s:4:"2016";}
I used Serialize() and got this (not the same as what came out of the session file):
a:12:{s:7:"user_id";i:4;s:15:"user_first_name";s:9:"FirstName";s:14:"user_last_name";s:8:"LastName";s:15:"user_last_login";s:10:"2016-06-03";s:11:"random_data";a:24:{s:2:"ID";i:83;s:3:"URL";a:1:{i:0;s:23:"https://www.example.com";}s:3:"API";N;s:4:"Date";s:10:"2016-06-08";s:4:"Year";s:4:"2016";}}
EDIT: It has to be the same format as the original string format (from file_get_contents()) because when I insert the serialize() string format it logs me out of the website.
You can use php functions serialize and unserialize to do that. By the way, the advantage of this way, that it saves type of, at least, standard php objects. For example, this code:
$o = new DateTime();
print_r(unserialize(serialize($o)));
returns DateTime Object
You can use JSON format:
json_encode(array);
For decode:
json_decode($json_string);
Related
Hi I'm having an issue where I try and pass a JSON Array through a url to another page and then retrieve the value using $_REQUEST. I've looked at other similar issues here and tried to get it working using http_build_query but still having issues and hoping someone can help me out.
This is the Array containing a JSON object I am trying to pass through. This array is contained in the variable $validationReport:
Array([0] => stdClass Object([resourceUri] => file:/home/testFile.txt#//#statements.12/#typeList.0/#enumLiterals.11 [severity] => WARNING [lineNumber] => 333 [column] => 9 [offset] => 7780 [length] => 24 [message] => Name should be less than 20 characters))
This is the url I have built:
<a href='../../validationReport.php?fileName=$fileName&fileSize=$fileSize&validationReport=$validationReport' target='_blank'>View Validation Report</a>
I'm trying to use these values on a different page and I'm using the following code to retrieve the values:
if (isset($_REQUEST['fileName']) && isset($_REQUEST['fileSize']) && isset($_REQUEST['validationReport'])) {
showReport($_REQUEST['fileName'], $_REQUEST['fileSize'], $_REQUEST['validationReport']);
}
Both fileName and fileSize are set fine and I can get their values but the $_REQUEST['validationReport'] is never set. Can anyone help me to figure out how to pass this value through the URL so that the $_REQUEST['validationReport'] will contain the Array with the JSON Object above.
You cannot send an object or display it on webPath
Try this:
json_encode(); to encode it to string
<a href='../../validationReport.php?fileName=$fileName&fileSize=$fileSize&validationReport=json_encode($validationReport[0])' target='_blank'>View Validation Report</a>
then decode it back to object
showReport($_REQUEST['fileName'], $_REQUEST['fileSize'], json_decode($_REQUEST['validationReport']));
I'm currently working on a site that's localized in a couple of languages and I'm running into a problem where json_decode is reformatting decimals in JSON strings depending on the locale. When the locale is set to "en" the decimals remain untouched. However, in the "fr_FR" locale they get changed to "13,3" for example.
Source JSON:
{"debug":[{"id":13.3}]}
Output for "en"
Array
(
[debug] => Array
(
[0] => Array
(
[id] => 13.3
)
)
)
Output for "fr_FR"
Array
(
[debug] => Array
(
[0] => Array
(
[id] => 13,3
)
)
)
Is there any reason json_decode does this? Is there a way to prevent it?
The bug is causing problems with the Gravity Forms Wordpress plugin, but I've already isolated the problem to the json_decode function.
It looks like the issue is with how PHP handles numeric values. json_decode is simply transforming 13.3 to a float, which on output or being converted to a string is the localized "13,3". However, PHP does not deal well with localized number formats.
As per this thread, using setlocale has resolved the issue (for the most part)
setlocale(LC_NUMERIC, 'C');
This question already has answers here:
How create an array from the output of an array printed with print_r?
(11 answers)
Closed 9 years ago.
I have, on a mysql table, a column in which are stored through a print_r on a previous step of the program.
So I have on a text cell of the mysql db this value:
Array
(
[id] => 129
[group_id] => 9
[rid] => 28
[date] => 2014-02-09 10:00:00
[real_time_start] => 00:00:00
[real_time_end] => 00:00:00
[site_id] => 1
[sub_site_id] => 2
[team1_id] => 9
[team2_id] => 13
[home] => 2
[result_type] => 2
[status] => 0
)
I have tried several ways, but with no success. How can I transform this one in a "real" php array?
Do you have any idea about it?
If you want to restore such data into readable PHP array do not use print_r() as its format is not easily readable by built-in parsers. You have several options:
convert it to JSON using json_encode() and then decode through json_decode,
convert to serialized format using var_export(), save to file and require() it,
use serialize() and unserialize(), as Leri said,
use YAML library (I recommend Symfony's one) and Yaml::dump() / Yaml::parse() your data.
The print_r() function prints a variable in a human-readable format. Therefore, it has no reverse equivalent.
If you’re wanting to transform a representation of an array to a plain text version for storage and back again, then use something like PHP’s serialize() and unserialize() functions.
To store an array to a table you should use serialize() function. When retrieving use unserialize() function to get the array back.
Thanks to all
The suggestion of Jasper was great, I've been able to convert the "print_r" output in a "serialize" one using the function proposed.
Now I will use serialize/unserialize to solve this problem.
I'm trying to access part of an StdClass that has a property #text. PHP uses '#' for comments so I'm having trouble getting PHP to parse it not as a comment. An example of the StdClass is below
stdClass Object
(
[artist] => stdClass Object
(
[name] => John Denver
[mbid] => 34e10b51-b5c6-4bc1-b70e-f05f141eda1e
[url] => http://www.last.fm/music/John+Denver
[image] => Array
(
[0] => stdClass Object
(
[#text] => http://userserve-ak.last.fm/serve/34/521025.jpg
[size] => small
and I've tried to access it with:
$json->artist->image[0]->#text
but how can I escape the '#' or tell php to interpret it differently. Or is there another format to find the #text property.
I also tried:
$json['artist']['image'][0]['#text']
but I get an error. I'm sure this is something simple but it's really got me at the moment.
You can access such properties with the following code:
$object->{'#text'}
It seems to be JSON data, so when decoding, you can also set the second parameter to true:
$json = json_decode($input, true);
Now you are able to use this:
$json['artist']['image'][0]['#text']
Citing another answer you can put the key in a variable an accessing it via this variable.
$var='myvarwithstrangecharacters$asdfas#';
$object->$var;//do whatever you want
from:
How do I access a PHP object attribute having a dollar sign?
I'm getting a PHP array from a web page (as a string).
It looks like :
Array
(
[k1] => Array
(
[a] => Array
(
[id] => 1
[age] => 60
)
[b] => Array
(
[id] => 2
[age] => 30
)
)
[k2] => v2
)
I want to parse it in python.
Does anyone have an idea how to do this?
Thanks,
Rivka
Edit:
This is really not a json, like a few people commented.
Thanks for the comments, and I updated the question.
That's not JSON, that's just how PHP prints arrays. If you want to create JSON of the array, check out json_encode for PHP. Then use Python's JSON library (or here for py3) to read it.
If I understood you correctly, you are using print_r on array to get that output. This is a visual representation of array only, you can't really parse it. For example:
array('Array'.PHP_EOL."\t(".PHP_EOL." [0] => test".PHP_EOL."\t)")
will look exactly like
array(array('test'));
You should use some real serializing function to do what you want(json,serialize etc.);