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
Related
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);
Is it possible in php to change the name used to create an associative array? I am using mongo in php but it's getting confusing using array() in both cases of indexed arrays and associative arrays. I know you can do it in javascript by stealing the Array.prototype methods but can it be done in php my extending the native object? it would be much easier if it was array() and assoc() they would both create the same thing though.
EDIT -------
following Tristan's lead, I made this simple function to easily
write in json in php. It will even take on variable from within
your php as the whole thing is enclosed in quotes.
$one = 'newOne';
$json = "{
'$one': 1,
'two': 2
}";
// doesn't work as json_decode expects quotes.
print_r(json_decode($json));
// this does work as it replaces all the single quotes before
// using json decode.
print_r(jsonToArray($json));
function jsonToArray($str){
return json_decode(preg_replace('/\'/', '"', $str), true);
}
In PHP there is no "name used to create an associative array" or "name used to create an indexed array". PHP Arrays are ordered maps like in many other scripting languages.
This means that you can use an array whichever way you please.
If you wanted an indexed array..
$indexedArray = array();
$indexedArray[] = 4; // Append a value to the array.
echo $indexedArray[0]; // Access the value at the 0th index.
Or even..
$indexedArray = [0, 10, 12, 8];
echo $indexedArray[3]; // Outputs 8.
If you want to use non integer keys with your array, you simply specify them.
$assocArray = ['foo' => 'bar'];
echo $assocArray['foo']; // Outputs bar.
I am working with a project that is coded in php OOP. I have created a form that post back to itself and gets those values and puts them into a predefined array format. I say predefined because this is the way the previous coder has done it:
$plane->add(array('{"name":"Chris","age":"22"}','{"name":"Joyce","age":"45"}'));
So when I get my values from the $_POST array, I thought it would be simple, so I tried
$plane->add(array("{'name':$customerName,'age':$customerAge}"));
This is triggering an error though, it seems it's passing the actual name of the variable in as a string instead of it's value. So how do I pass those values in to that function. While we are on it, can someone explain what kind of array that is, I thought arrays were always $key=>value set, not $key:$value.
As other comments and answers have pointed out, the data is being serialized in a format known as JSON. I suggest reading up on json_encode() and json_decode()
To make your example work, you would have to do:
$data = array("name" => $customerName, "age" => $customerAge);
$plane->add(array(json_encode($data));
That looks like json:
http://sandbox.onlinephpfunctions.com/code/e1f358d408a53a8133d3d2e5876ef46876dff8c6
Code:
$array = json_decode('{"name":"Chris","age":"22"}');
print_r( $array );
And you can convert an array to json with:
$array = array("Customer" => "John");
$arrayJson = json_encode( $array);
So to put it in your context:
$array = array("Name"=>"Chris", "age" => 22);
$array2 = array("Name"=>"John", "age" => 26);
$plane->add(array( json_encode( $array),json_encode( $array2) );
It looks like it could be JSON, but might not be.
Be careful to quote everything like they have done, you didn't have any quotes around the name or age.
I've added the same sort of quotes, and used the backslashes so that PHP doesn't use them to end the string:
$plane->add(array("{\"name\":\"$customerName\",\"age\":\"$customerAge\"}"));
Be wary of user data, if $customerName and $customerAge come from POST data, you need to properly escape them using a well tested escaping function, not something you just hack together ;)
It looks like your array is an array of JSON encoded arrays. Try using:
$plane->add(array('{"name":"' . $nameVar . '","age":"' . $ageVar . '"}', ...));
If you use the following:
echo json_encode(array('name' => 'Me', 'age' => '75'), array('name' => 'You', 'age' => '30'));
You will get the following string:
[{"name":"Me","age":"75"},{"name":"You","age":"30"}]
I believe you are getting an error because what you are trying to pass to the function is not JSON while (It looks like ) the function expects an array json strings, Manually trying to write the string might not be a good idea as certain characters and type encode differently. Best to use json_encode to get you json string.
$plane->add(array(json_encode(array('name'=>$customerName,'age'=>$customerAge))));
I've been using a few javascript libraries, and I noticed that most of them take input in this form: [{"foo": "bar", "12": "true"}]
According to json.org:
So we are sending an object in an array.
So I have a two part question:
Part 1:
Why not just send an object or an array, which would seem simpler?
Part2:
What is the best way to create such a Json with Php?
Here is a working method, but I found it a bit ugly as it does not work out of the box with multi-dimensional arrays:
<?php
$object[0] = array("foo" => "bar", 12 => true);
$encoded_object = json_encode($object);
?>
output:
{"1": {"foo": "bar", "12": "true"}}
<?php $encoded = json_encode(array_values($object)); ?>
output:
[{"foo": "bar", "12": "true"}]
Because that's the logical way how to pass multiple objects. It's probably made to facilitate this:
[{"foo" : "bar", "12" : "true"}, {"foo" : "baz", "12" : "false"}]
Use the same logical structure in PHP:
echo json_encode(array(array("foo" => "bar", "12" => "true")));
An array is used as a convenient way to support multiple parameters. The first parameter, in this case, is an object.
Question one:
JSON is just a way of representing an object and/or and array as a string. If you have your array or object as a string, it is much easier to send it around to different places, like to the client's browser. Different languages handle arrays and objects in different ways. So if you had an array in php, for example, you can't send it to the client directly because it is in a format that only php understands. This is why JSON is useful. It is a method of converting an array or object to a string that lots of different languages understand.
Question two:
To output an array of objects like the above, you could do this:
<?php
//create a test array of objects
$testarray = array();
$testarray[] = json_decode('{"type":"apple", "number":4, "price":5}');
$testarray[] = json_decode('{"type":"orange", "number":3, "price":8}');
$testarray[] = json_decode('{"type":"banana", "number":8, "price":3}');
$testarray[] = json_decode('{"type":"coconut", "number":2, "price":9}');
$arraycount = count($testarray);
echo("[");
$i = 1;
foreach($testarray as $object)
{
echo(json_encode($object));
if($i !== $arraycount)
{
echo(",");
}
$i += 1;
}
echo("]");
?>
This will take an array of objects and loop over them. Before we loop over them, we output the opening square bracket.
Then, for each object in the array, we output it encoded to JSON plus a comma after each one. We count the number of iterations so that we don't output a comma at the end.
I have a php file with some arrays in it. I want to modify one of these arrays and write it back to the file. For e.g. say file test.php has contents -
<?php
$arr1 = array("a"=>"b", "c" =>"d");
$arr2 = array("a2" => "b2", "c2" => "d2");
i want to change $arr1 so that test.php now looks like -
<?php
$arr1 = array("a"=>"b", "c" =>"d", "e"=>"f");
$arr2 = array("a2" => "b2", "c2" => "d2");
I do not know what arrays are present in the file beforehand.
Edit: i am not adding any variables to the array, only another key value pair. The problem is that the array is part of a file with more arrays in it about which I won't always be aware. I can achieve this if there was only one array in the file, but want to know if it is possible to do this with multiple arrays.
You could introduce another "global" array
$arr = array('arr1' => array("a"=>"b", "c" =>"d"), 'arr2' =>("a2" => "b2", "c2" => "d2"));
and serialize it
$serArr = serialize($arr);
//write to file here
When you read the file, just unserialize its content so you have the "global" array with it's sub-arrays, modify the values you need, serialize it and write it back.
Keep in mind that this can be a huge performance issue when you write big arrays.
If you are within a function (i.e. not in global scope) get_defined_vars() might be a good bet. You'd just need to include the file in a closed scope and return it's keys to get all variable names in the file.
<?php
$arr1 = array("a"=>"b", "c" =>"d");
$newarr=array("d"=>"f");
$arr1+=$newarr;
it's has been 5 years, but i want to give simple way that work for me.