save a multidimensional array to txt - php

Hi I have an array that stores products. Here is an example of the first product:
$_SESSION['pricebook']['product1'] = array(
'name' => 'product1',
'description'=>'Board my Cat(s)!',
'price'=>25.95,
);
And I have an array for the cart that stores each product a user selects from the pricebook array.
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}
How would I write the cart into an orders.txt file? Everything I have tried has given me the "Array Notice: Array to string conversion" error.
Note: the product is added to the cart as so:
if (isset($_GET["product1"]) && $_GET["product1"]=="Add") {
$pid = $_GET["name"];
if (!isset($_SESSION['cart'][ $pid ])) { $_SESSION['cart'][ $pid ]; }
array_push($_SESSION['cart'][ $pid ]);
}
Also is there any way that it can be saved to a txt file in a human readable format kinda like a receipt?

You can use PHP's serialize() for this.
Generates a storable representation of a value.
This is useful for storing or passing PHP values around without losing their type and structure.
To make the serialized string into a PHP value again, use unserialize().
To save, your code could look like this
$representation = serialize($_SESSION['cart']);
// save $representation to your txt file/whatever
and to load the values, just do as is said in the manual
// load data into $representation
$_SESSION['cart'] = unserialize($representation);
If you want a prettier format, you can use json_encode() with the JSON_PRETTY_PRINT flag set
$representation = json_encode($_SESSION['cart'], JSON_PRETTY_PRINT);
// save $representation to your txt file/whatever
// load data into $representation
$_SESSION['cart'] = json_decode($representation);

You could try:
$handle = fopen('orders.txt', 'w+'); // change this based on how you would like to update the file
fwrite($handle, print_r($_SESSION['cart']), true);
fclose($handle);

Use either serialize or json_encode.
You could use serialize() like this
$t = serialize($_SESSION['cart']);
file_put_contents('filename.txt', $t);
Or json_encode()
$t = json_encode($_SESSION['cart']);
file_put_contents('filename.txt', $t);
serialize will work a tiny little bit faster, but is PHP specific, while json_encode will produce a JSON string that can be fed into anything, including a toaster :D The JSON string also leaves a smaller footprint than the serialized one.

Related

How to convert plaintext to array? [duplicate]

I just want to quickly store an array which I get from a remote API, so that i can mess around with it on a local host.
So:
I currently have an array.
I want to people to use the array without having to get it from the API.
There are no needs for efficiency etc here, this isnt for an actual site just for getting some sanitizing/formatting methods made etc
Is there a function like store_array() or restore_arrray() ?!
The best way to do this is JSON serializing. It is human readable and you'll get better performance (file is smaller and faster to load/save). The code is very easy. Just two functions
json_encode
json_decode
Example code:
$arr1 = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
file_put_contents("array.json",json_encode($arr1));
# array.json => {"a":1,"b":2,"c":3,"d":4,"e":5}
$arr2 = json_decode(file_get_contents('array.json'), true);
$arr1 === $arr2 # => true
You can write your own store_array and restore_array functions easily with this example.
For speed comparison see benchmark originally from Preferred method to store PHP arrays (json_encode vs serialize).
If you don't need the dump file to be human-readable, you can just serialize() the array.
storing:
file_put_contents('yourfile.bin', serialize($array));
retrieving:
$array = unserialize(file_get_contents('yourfile.bin'));
Use serialize and unserialize
// storing
$file = '/tmp/out.data';
file_put_contents($file, serialize($mydata)); // $mydata is the response from your remote API
// retreiving
$var = unserialize(file_get_contents($file));
Or another, hacky way:
var_export() does exactly what you want, it will take any kind of variable, and store it in a representation that the PHP parser can read back. You can combine it with file_put_contents to store it on disk, and use file_get_contents and eval to read it back.
// storing
$file = '/tmp/out.php';
file_put_contents($file, var_export($var, true));
// retrieving
eval('$myvar = ' . file_get_contents($file) . ';');
Another fast way not mentioned here:
That way add header with <?php start tag, name of variable \$my_array = with escaped \$ and footer ?> end tag.
Now can use include() like any other valid php script.
<?php
// storing
$file = '/tmp/out.php';
$var = ['a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5];
file_put_contents($file,
"<?php\n\$my_array = "
.var_export($var, true)
.";\n?>"
);
// retrieving as included script
include($file);
//testing
print_r($my_array);
?>
out.php will look like this
<?php
$my_array = array (
'a'=>1,
'b'=>2,
'c'=>3,
'd'=>4,
'e'=>5
);
?>
You can use serialize to make it into a string to write to file, and the accompanying unserialize to return it to an array structure.
I'd suggest using a language independent structure though, such as JSON. This will allow you to load the files using different languages than PHP, in case there's a chance of that later. json_encode to store it and json_decode($str, true) to return it.
Talking about php use, for performance sake, avoid encoding and decoding everything, just save array with:
file_put_contents('dic.php', "<?php \n".'$dic='.var_export($dic, true).';');
and call normally with
include "dic.php";
Use php's serialze:
file_put_contents("myFile",serialize($myArray));
I made a tiny library (~2 KB; <100 lines) that allows you to do just this: varDx
It has functions to write, read, modify, check and delete data.
It implements serialization, and therefore supports all data types.
Here's how you can use it:
<?php
require 'varDx.php';
$dx = new \varDx\cDX; //create an object
$dx->def('file.dat'); //define data file
$val1 = "this is a string";
$dx->write('data1', $val1); //writes key to file
echo $dx->read('data1'); //returns key value from file
In your specific case:
$array1 = array(
"foo" => "bar",
"bar" => "foo",
);
//writing the array to file
$dx->write('myarray', $array1);
//reading array from file
$array2 = $dx->read('myarray')
//modifying array in file after making changes
$dx->write('myarray', $array2);

Serialized multidimensional stored in MySQLi does not print past first array

Confusing title, the basics are that I'm saving a fully sorted and ordered multidimensional array from a script and into MySQL. I then, on another page, pull it from the database and unserialize it, and then proceed to print it out with this,
$s = "SELECT * FROM gator_historical_data WHERE channelid = '{$chanid}'";
$r = $link->query($s);
$comboarray = array();
while ($row = mysqli_fetch_assoc($r)) {
$comboarray[] = unserialize($row['dataarray']);
}
foreach ($comboarray as $item) {
$desc = $item['content']['description'];
$title = $item['content']['title'];
$datetime = $item['datetime'];
// ... ^^^ problems getting array data
}
The problem is that it doesn't take the full array from MySQL, only the first entry and thus only prints the first 'array'. So where the returned value from dataarray looks like this (var_dump): http://pastebin.com/raw.php?i=Z0jy55sM the data stored into the unserialized $comboarray only looks like this (var_dump): http://pastebin.com/raw.php?i=Ycwwa924
TL;DR: Pulling a serialized multidimensional array from a database, unserializing and it loses all arrays after the first one.
Any ideas what to do?
The string you've got is a serialized string plus something more at the end that is also a serialized string again and again:
a:3:{s:6:"source";s:25:"World news | The Guardian";s:8:"datetime ...
... story01.htm";}}a:3:{s:6:"source";s:16:"BBC News - World";
^^^
This format is not supported by PHP unserialize, it will only unserialize the first chunk and drop everything at the end.
Instead create one array, serialize it and store that result into the database.
Alternatively you can try to recover for the moment by un-chunking the string, however in case the paste was done right, there are more issues. But on the other hand the paste obvious isn't the done fully correct.

extract details from from string

I have a string in my database along with type varchar
{"available":"","bind":"0","hours":{"00:00":{"available":"","bind":"0","info":"","notes":"","price":"","promo":"","status":"none"}},"hours_definitions":[{"value":"00:00"}],"info":"","notes":"","price":"100","promo":"","status":"available"}
How do I extract the price from this?
That string is valid JSON data, so you all you need to do is decode to an array for PHP to read. Like so:
$data = json_decode($string);
$price = $data->price;
To force it to be an array instead of an object, pass true to the second argument of json_decode, like so:
$data = json_decode($string, true);
$price = $data['price'];
That looks like JSON to me, so the steps are really simple:
1. Use json_decode($response, true) to convert from JSON to an array.
2. Treat as a normal array.
As such, the following code should work fine for you
$info = json_decode($jsonCode, true);
$price = $info['price'];
And the price will be stored in $price, or just $info['price'] if you don't need another variable for it.
json_decode()'s second argument means that it will return associative arrays (like the one you have here) as an array, rather than an object. It's usually more useful that way, however you could always set it to false (or just leave it out, as false is the default).
See json_decode's PHP documentation page for more info on its arguments.

PHP/MYSQL array storing and retrieval issue

I want to store short arrays in a field. (I realize there are reasons to break the array up into items and store separately, but I'm opting for a simple storage option at the expense of less capability.)
My code to create the array is as follows:
$str = "one,two,three,four";
$array = explode (",",$str)
I then store into a text field in mysql using an insert statement It seems to store fine. In PhPAdmin, it shows ARRAY in the field and if I just echo $array, it prints "ARRAY".
The problem is occurring when I try to retrieve data.
I am retrieving using
while($row = mysql_fetch_array($res)) {
$array = $row['list']; //that's the field it is stored in
echo $array; // echoes "ARRAY"
//so far so good. However, when I then try to print out the contents of the array, I get error messages. I have tried using implode and also for each.
$text = implode(",", $array);//yields error message improper argument in implode function
foreach($array as $val) {
echo $val;
} //yields error message improper argument for for each statement
}
Could my entry in the dbase not be a proper array? What could the problem be? Thanks for any suggestions.
The usual approach to storing an array in this way is to serialize the data before input, and unserialize it upon retrieval.
$array = array('one', 'two', 'three', 'four');
$stringToStore = serialize($array);
Later:
while($row = mysql_fetch_array($res)) {
$array = unserialize($row['list']);
var_dump($array);
}
What you're inserting is not an array, just what PHP has evaluated your array as being in string form. To store an array in MySQL without properly normalizing your data you'll need to serialize it. Basically you'd want to do something like:
$serialized = implode(',', $arrayToStore);
and then store that in MySQL. On its way out then you'll do:
$unserialized = explode(',', $arrayFromMySQL);
I think you can use serialize and also (if you don't use serialize) if your array string is as follows
$str = "one,two,three,four";
then why you are making it an array before inserting it into your database, I think you can insert the string directly and when you need to use your string as an array then you can simply retrieve the string from database and make it an array using explode like
while($row = mysql_fetch_array($res)) {
$array = explode(",", $row['list']); // "one,two,three,four"
echo $array[0]; // one

How to deserialize this string into a PHP array of key => value pairs?

I'm calling the script at: http://phat-reaction.com/googlefonts.php?format=php
And I need to convert the results into a PHP array format like the one I'm currently hard coding:
$googleFonts = array(
"" => "None",
"Abel"=>"Abel",
"Abril+Fatface"=>"Abril Fatface",
"Aclonica"=>"Aclonica",
etc...
);
The php returned is serialized:
a:320:{
i:0;
a:3:{
s:11:"font-family";
s:32:"font-family: 'Abel', sans-serif;";
s:9:"font-name";
s:4:"Abel";
s:8:"css-name";
s:4:"Abel";
}
i:1;
a:3:{
s:11:"font-family";
s:38:"font-family: 'Abril Fatface', cursive;";
s:9:"font-name";
s:13:"Abril Fatface";
s:8:"css-name";
s:13:"Abril+Fatface";
}
etc...
How can I translate that into my array?
You can do this by unserializing the data (using unserialize()) and then iterating through it:
$fonts = array();
$contents = file_get_contents('http://phat-reaction.com/googlefonts.php?format=php');
$arr = unserialize($contents);
foreach($arr as $font)
{
$fonts[$font['css-name']] = $font['font-name'];
}
Depending on what you're using this for, it may be a good idea to cache the results so you're not fetching external data each time the script runs.
Use unserialize(): http://www.php.net/unserialize

Categories