I've outputted my array to file using the print_r($myArray, true) method, but am having trouble re-importing it as an array.
I keep returning a string with the array, not the array itself. I've tried a few different combinations including print_r and serialize, but can't seem to get it right. What am I missing?
Here's what I have:
$myArray = print_r(file_get_contents($logFile), true);
for reference the log file content looks like so:
Array
(
[0] => Array
(
[0] => blah
[1] => blah
)
...
Thanks
EDIT: Solution - Here is what I came up with:
I changed the file contents to include php tags and declared the array there using var_export instead of print_r.
Here is what I used as my content string when writing to file:
<?php $myArray = '.var_export($myArray, true).'; ?'.'>
From there it was a simple include to get the array back.
You should just store the array as ... an array, like so:
file_put_contents('myfile.txt', '<?php return ' . var_export($array, true) . '; ?>');
Then, to read:
$array = include 'myfile.txt';
See also: var_export()
Related
So I got this array:
$list = simplexml_load_file('http://feu01.ps4.update.playstation.net/update/ps4/list/eu/ps4-updatelist.xml');
if($list) {
$data = array('firmware' => $list->region->system_pup[0]['label']);
header('Content-Type: application/json');
echo json_encode($data);
}
And it outputs this:
{"firmware":{"0":"5.01"}}
But there's also a zero there. How do I remove it from the array so it's like this:
{"firmware":"5.01"}
This is a SimpleXMLElement result which you need to convert to a string if you want that data:
$data = array('firmware' => (string) $list->region->system_pup[0]['label']);
In JSON form it looks like an associative array, which it isn't, so the [0] trick which normally works to navigate to it won't.
I have a file, in which I saved data in array format and later I want to read this data into a variable and this variable must behave like an array.
Suppose I have a file on my pc : C:/test.txt and it contains an array :
Array
(
[first_name] => John
[last_name] => Doe
[email] => johndoe#gmail.com
)
Now I am fetching this data using below method :
$myfile = fopen("C:/test.txt", "r");
$test = fread($myfile,filesize("C:/test.txt"));
Now when I print $test it shows the data like array but when I check the datatype of this variable then it shows String.
I have also converted this variable into array using type casting :
$test1 = (Array) $test;
But when tried to fetch any index from $test1 then it show Illegal string error.
So can somebody help me out.
Try this
$file = "C:/test.txt";
$document = fopen($file,'r');
$contents = fread($document, filesize($file));
fclose($document);
this will give you a array $contents
print_r($contents);
C:/test.php
<?php
return array(
'first_name' => null,
'last_name' => null,
'email' => 'new',
);
another file:
<?php
$array = inclde('C:/test.php');
Or save json in file C:/test.json
{"first_name":null,"last_name":null,"email":"new"}
and in another file:
<?php
$json = file_get_contents('C:/test.json');
$array = json_decode($json, true);
Do this:
// $myarray is the array
file_put_contents('my_file', serialize($myarray));
// Later ...
$array = unserialize(file_get_contents('my_file'));
You can guess what serialize or unserialize does. But read more in docs to learn more specifically.
#VladimirKovpak 's answer will work too, but for simple arrays. Using serialization, you can save nearly any object, and get it back.
If you need more control over serialization process, look into magic methods __sleep and __wakeup from docs.
I have an array that is filled with different sayings and am trying to output a random one of the sayings. My program prints out the random saying, but sometimes it prints out the variable name that is assigned to the saying instead of the actual saying and I am not sure why.
$foo=Array('saying1', 'saying2', 'saying3');
$foo['saying1'] = "Hello.";
$foo['saying2'] = "World.";
$foo['saying3'] = "Goodbye.";
echo $foo[array_rand($foo)];
So for example it will print World as it should, but other times it will print saying2. Not sure what I am doing wrong.
Drop the values at the start. Change the first line to just:
$foo = array();
What you did was put values 'saying1' and such in the array. You don't want those values in there. You can also drop the index values with:
$foo[] = 'Hello.';
$foo[] = 'World.';
That simplifies your work.
You declared your array in the wrong way on the first line.
If you want to use your array as an associative Array:
$foo=Array('saying1' => array (), 'saying2' => array(), 'saying3' => array());
Or you can go for the not associative style given by Kainaw.
Edit: Calling this on the not associative array:
echo("<pre>"); print_r($foo); echo("</pre>");
Has as output:
Array
(
[0] => saying1
[1] => saying2
[2] => saying3
[saying1] => Hello.
[saying2] => World.
[saying3] => Goodbye.
)
Building on what #Answers_Seeker has said, to get your code to work the way you expect it, you'd have to re-declare and initialise your array using one of the methods below:
$foo=array('saying1'=>'Hello.', 'saying2'=>'World.', 'saying3'=>'Goodbye.');
OR this:
$foo=array();
$foo['saying1'] = "Hello.";
$foo['saying2'] = "World.";
$foo['saying3'] = "Goodbye.";
Then, to print the contents randomly:
echo $foo[array_rand($foo)];
How would I setup an associative array to reference specific values at different sections of a page. My function:
<?php
function park_data($park_page_id) {
$data = array();
if($park_page_id){
$data = mysql_fetch_assoc(mysql_query("SELECT * FROM `park_profile` WHERE `park_id` = $park_page_id"));
return $data;
}
}
?>
My print_r:
<?php
print_r (park_data(1));
?>
Produces the following associative array:
Array ( [park_id] => 1 [park_name] => Kenai Fjords [park_address] => 1212 4th Avenue [park_city] => Seward [park_state] => Alaska [park_zip] => 99664)
How would I print just the [park_name] value from this array?
From the docs:
As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.
// on PHP 5.4
print_r(park_data(1)['park_name']);
// earlier versions
$tmp = park_data(1);
print_r($tmp['park_name']);
$park=park_data(1);
echo $park['park_name'];
To output custom formatted text in general, and in this case to output only a single array's key value, use echo, because print_r() called on an array displays the whole array's structure and content, and that's not what you want:
<?php
// code
$park_data=park_data(1);
echo $park_data["park_name"];
// code
?>
I been looking thru the posts here all day but can't figure out what I'm doing wrong. (I'm new to php and json)
Here is my code that work.
$json = '{"id":1234,"img":"1.jpg"}';
$data = json_decode($json, true);
echo $data["img"];
But when the json respond is this
$json = '{"demo1":[{"id":1234,"img":"1.jpg"}],"userId":1}';
it's a big harder for me. then img is a child of demo1? How to get it?
Thx. :)
Figuring out the array indices
As you're new to PHP, I'll explain how to figure out the array indces of the required array value. In PHP, there are many functions for debugging — print_r() and var_dump() are two of them. print_r() gives us a human-readable output of the supplied array, and var_dump() gives us a structured output along with the variable types and values.
In this case, print_r() should suffice:
$json = '{"demo1":[{"id":1234,"img":"1.jpg"}],"userId":1}';
$data = json_decode($json, true);
// wrap the output in <pre> tags to get a prettier output
echo '<pre>';
print_r($data);
echo '</pre>';
This will produce the following output:
Array
(
[demo1] => Array
(
[0] => Array
(
[id] => 1234
[img] => 1.jpg
)
)
[userId] => 1
)
From there, it should be pretty easy for you to figure out how to access the required vaule.
$data['demo1'][0]['img'];
Creating a helper function for ease of use
For ease of use, you can create a helper function to make this process easier. Whenever you want to view the contents of an array, you can simply call dump_array($array); and be done with it. No more messing around with <pre> tags or print_r().
Function code:
function dump_array($array) {
echo '<pre>' . print_r($array, TRUE) . '</pre>';
}
Usage example:
$arr = ['foo' => range('a','i'), 'bar' => range(1,9)];
dump_array($arr);
after decoding :
echo $data->demo[0]->img;
Basically, a { in JSON leads to a -> (it's an object).
And a [ to a [], it's an array.