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);
Related
I have this code
$status = array(
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=>array(),
);
echo json_encode($status);
This function return json:
{"message":"error","club_id":275,"status":"1","membership_info":[]}
But I need json like this:
{"message":"error","club_id":275,"status":"1","membership_info":{}}
use the JSON_FORCE_OBJECT option of json_encode:
json_encode($status, JSON_FORCE_OBJECT);
Documentation
JSON_FORCE_OBJECT (integer)
Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty. Available since PHP 5.3.0.
Or, if you want to preserve your "other" arrays inside your object, don't use the previous answer, just use this:
$status = array(
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=> new stdClass()
);
$status = array(
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=>(object) array(),
);
By casting the array into an object, json_encode will always use braces instead of brackets for the value (even when empty).
This is useful when can't use JSON_FORCE_OBJECT and when you can't (or don't want) to use an actual object for the value.
There's no difference in PHP between an array and an "object" (in the JSON sense of the word). If you want to force all arrays to be encoded as JSON objects, set the JSON_FORCE_OBJECT flag, available since PHP 5.3. See http://php.net/json_encode. Note that this will apply to all arrays.
Alternatively you could actually use objects in your PHP code instead of arrays:
$data = new stdClass;
$data->foo = 'bar';
...
Maybe it's simpler to handle the edge case of empty arrays client-side.
I know this is an old question, but it's among the first hits on Google, so I thought I should share an alternative solution.
Rather than using standard PHP arrays, in PHP 7+ you can instead use Map() as part of the Data Structure extension. Documentation.
A Map object has practically identical performance as arrays and also implements ArrayAccess so it can be accessed as a regular array. Contrary to a standard array, however, it will always be associative and works as expected with json_encode. It also has some other minor benefits like object keys and better memory handling.
Some example usage:
use Ds\Map;
$status = new Map([
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=>array(),
]);
$map = new Map();
print json_encode($map); // {}
$map = new Map();
$map["foo"] = "bar";
print json_encode($map); // {"foo":"bar"}
print $map["foo"]; // bar
$map = new Map();
$map[1] = "foo";
$map[2] = "bar";
$map[3] = "baz";
print json_encode($map); // {"1":"foo","2":"bar","3":"baz"}
While this may not be considered elegant, a simple string replace can effectively address this.
str_replace("[]", "{}", json_encode($data));
This mitigates the issue of JSON_FORCE_OBJECT converting a normal array into an object.
On the client side to comply with a whole bunch of complicated legacy code, I need JSON to look like this:
A. {"book":[{"title":"War and Peace.","author":"Leo Tolstoy"}]}
where the "value" side of the Dictionary is an array containing a dictionary e.g. [{}].
However, when retrieving a random item, my server code is outputting the following:
B. {"book":{"title":"War and Peace","author":"Leo Tolstoy"}}
where the "value" side is just a dictionary e.g. {}.
How can I generate the JSON so it looks like A instead of B?
Here is what is currently happening on the server to generate B:
The data is actually stored in JSON as:
$str = '[{"title":"War and Peace","author":"Leo Tolstoy"}]';
The code that outputs a random item is:
$array = json_decode($str, true);
$rand = $array[array_rand($array)];
echo json_encode(array('book'=>$rand));
How can I put the dictionary on the value side inside square brackets e.g. [{}]?
simply wrap you $rand variable inside bracket []. Curious to know What is the purpose of array_rand() here?
<?php
$str = '[{"title":"War and Peace","author":"Leo Tolstoy"}]';
$array = json_decode($str, true);
$rand = $array[array_rand($array)];
echo json_encode(array('book'=>[$rand]));
?>
DEMO: https://3v4l.org/dZJRn
How can I create JSON using PHP with data which contains JSON without including a bunch of escape characters in the JSON, and without converting JSON first to an array or object, and then back to JSON?
<?php
/*
GIVEN: Data from DB contained in array $a.
I know that sometimes JSON shouldn't be stored in a DB, but please assume this is a good case for doing so.
*/
$a[0]=json_encode(['a'=>5,'b'=>'hello']);
$a[1]=json_encode(['a'=>2,'b'=>'how are you']);
$a[2]=json_encode(['a'=>7,'b'=>'goodby']);
$o=[
['x'=>321,'y'=>$a[0]],
['x'=>123,'y'=>$a[1]],
['x'=>111,'y'=>$a[2]],
];
echo('<pre>'.print_r($o,1).'</pre>');
echo(json_encode($o));
/*
Undesired result containing a bunch of escape characters. Granted, they are benign, however, will increase network trafic.
[{"x":321,"y":"{\"a\":5,\"b\":\"hello\"}"},{"x":123,"y":"{\"a\":2,\"b\":\"how are you\"}"},{"x":111,"y":"{\"a\":7,\"b\":\"goodby\"}"}]
*/
$o=[
['x'=>321,'y'=>json_decode($a[0])],
['x'=>123,'y'=>json_decode($a[1])],
['x'=>111,'y'=>json_decode($a[2])],
];
echo('<pre>'.print_r($o,1).'</pre>');
echo(json_encode($o));
/*
Desired result, however, is there a more efficient way to do this?
[{"x":321,"y":{"a":5,"b":"hello"}},{"x":123,"y":{"a":2,"b":"how are you"}},{"x":111,"y":{"a":7,"b":"goodby"}}]
*/
No, there is no faster way then to decode, mutate and encode again.
You could however combine the decoding code closely with your database queries. If you have a data model class, you would do the decoding there, so that the code that calls this service will never see the JSON, but always the decoded data.
Then, again, in the data model, where you write to the database, you would perform the JSON encoding at the last moment.
This way you hide the JSON factor behind the walls of the data layer, and the rest of the application will not have to be aware of that.
Manipulating JSON directly
Another solution consists of writing a library that can juggle with JSON, giving possibilities to set values inside JSON without the caller having to decode/encode. This option requires much more code (or you could find an existing library), and so it is not really my first recommendation. But here is a naive example of a function that could exist in that library:
function json_set($json, $path, $value) {
$arr = json_decode($json, true);
$ref =& $arr;
$props = explode("/", $path);
$finalProp = array_pop($props);
foreach ($props as $key) {
if (!isset($ref[$key])) $ref[$key] = [];
$ref =& $ref[$key];
}
$obj = json_decode($value);
$ref[$finalProp] = $obj ? $obj : $value;
return json_encode($arr);
}
This allows you to provide an existing JSON string, a path pointing to a certain spot inside that JSON, and a value that should be put there. That value could itself also be JSON.
Here is how you would use it in your case, given the JSON values in $a which you got from the database:
$o=json_encode([
['x'=>321],
['x'=>123],
['x'=>111],
]);
$o = json_set($o, '0/y', $a[0]);
$o = json_set($o, '1/y', $a[1]);
$o = json_set($o, '2/y', $a[2]);
echo $o;
Output:
[{"x":321,"y":{"a":5,"b":"hello"}},
{"x":123,"y":{"a":2,"b":"how are you"}},
{"x":111,"y":{"a":7,"b":"goodby"}}]
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.
I have a file that has some values inside, an ordinary txt file, but I have made it look like an array
tekstovi.php
That looks like this
'1' => 'First',
'2' => 'Second',
'3' => 'Third',
Or someone have a better solution for file look :)
From that file I want to make a new array $promenjive in scope, so what is the best way to make an array from a file in php? It is easy to make explode in an ordinary array, but I don't know how to put all that in a multidimensional array :)
why don't you just make a .php file which will return an array, something like:
// somefile.php
return array(
'key1' => 'value1',
'key2' => 'value2'
);
and when you need it:
$something = require('/path/to/somefile.php');
echo $something['key1'];
Or someone have a better soluton for [the] file [format]
Create an INI file and use parse_ini_file().
If it's just an array only read by PHP, simply use include/require.
Have the file store the values in some sort of data-storing file type, e.g. xml, json, csv
PHP numerous ways of parsing and retrieving that data meaningfully. My recommendation is to use json, so with your example above it would be:
{"1":"First","2":"Second","3":"Third"}
And the corresponding PHP method to decode it:
json_decode($contents, true)
Check out the http://php.net/manual/en/function.json-decode.php for the method's full documentation, note that I set the 2nd optional argument to true since you're parsing an associative array, otherwise it will convert the data into an Object
Use JSON:
{
"foo" : "bar",
"baz" : [2, 3, 5, 7, 11]
}
PHP:
$content = file_get_contents('path/to/file');
$array = json_decode($content, true);
Et voila'.
parse_ini_file is a good solution with for a 1 or 2 dimensional array but if you need a more deeply nested structure you can use json.
$config = json_decode(file_get_contents($configFile)); // return an object, add true as a second parameter for an array instead
with the file looking something like
{
"1":"First",
"2":"Second",
"3":"Third"
}
if JSON formatting is not palatable for you then YAML or XML might be an option.
You don't need to do much, you can just create a variable in one file, and after including it will be available in the other.
file1.php:
$x = 5;
file2.php:
include file1.php
echo $x; //echoes 5