How Do I Write An Array To A File PHP? [duplicate] - php

This question already has answers here:
Print array to a file
(14 answers)
How do I store an array in a file to access as an array later with PHP?
(8 answers)
Closed 8 months ago.
I am trying to write an array to a file in php. If I do
$var = "Var";
fwrite($file, "<?php \$var = '$var';");
and I echo $var in the new file it will return "Var". But if I do the same thing with an array it will return "Array". How can I fix this?

The var_export() function does exactly what you want: it outputs a variable in a way it can be used in a .php file. Please note that when using var_export, you should drop the quotes around your variable in the output string.
fwrite($file, "<?php \$var = ".var_export($var, true).";");

You need to turn the array into a string that is separated by a comma. This is one of those problems where you will run into lots of edge cases. For instance, the below code will fail if one of the elements in the array contains a ' single quote character.
<?php
$hello = 'Hello';
$world = 'World';
$integer = 100;
$array = [
$hello,
$world,
$integer
];
function add_quotes($e) {
if (is_string($e))
return sprintf("'%s'", $e);
else
return $e;
}
$php_string = '<?php
$array = [';
$php_string .= implode(',', array_map('add_quotes', $array));
$php_string .= '];';
$fp = fopen('output.php', 'w');
fwrite($fp, $php_string);
This will output
<?php
$array = ['Hello','World',100];

How you fix things depends very much on what you want to do with the stored data.
The simple example is to write each element separately:
<?php
$arr = ['Apple','Orange','Lemon'];
$fh = fopen('myFile.csv', 'w');
foreach($arr as $el) {
fwrite ($fh, "$el\n"); // add a new line after each element to delimit them
}
fclose($fh);
You could create a CSV file with fputcsv():
<?php
$arr = ['Apple','Orange','Lemon'];
$fh = fopen('myFile.csv', 'w');
fputcsv($fh, $arr);
fclose($fh);
You could write JSON data:
<?php
$arr = ['Apple','Orange','Lemon'];
file_put_contents('myFile.json', json_encode($arr));
If you're feeling bold you could create an XML file (no snippet for this one, but trust me, it can be done).
You could write serialized PHP data (see serialize()) - not recommended.
Or you could create your own format for your specific application.

Related

PHP array from loop to string [duplicate]

This question already has answers here:
Convert flat array to a delimited string to be saved in the database
(13 answers)
Closed 5 years ago.
I import a CSV file with the following code (extract):
while(($line = fgetcsv($csvFile, 0, "\t")) !== FALSE){
//some mysql insert
$aff[] = $line[12];
}
Now I need to get some items to use them later in the code. I added the $aff variable, but was not able to create a string from the items.
The final string should be seperated with a comma: a, b, c
How can I do that? If I print the $aff out, it only says "Array".
Use php's implode function -
http://php.net/manual/en/function.implode.php
$string = implode(",", $aff);
That will create a string separated by commas from your array.
This is a very basic PHP question. Googling something like concatenate array or something should give you the answer right away. The correct approach would be to use the function implode with a separator:
echo implode(', ', $aff);
Also note that you should create the array outside of your loop if you don't already do this:
// Create empty array
$aff = [];
while(($line = fgetcsv($csvFile, 0, "\t")) !== FALSE){
//some mysql insert
$aff[] = $line[12];
}
// Output the array
echo implode(', ', $aff);
Try this, use concatenating assignment operato and do rtrim and you got your solution
$str = "";
while(($line = fgetcsv($csvFile, 0, "\t")) !== FALSE){
//some mysql insert
$str .= $line[12].", ";
}
echo echo rtrim($str,", ");

Reading text file and assigning key pair value in variable in PHP

I would like to read text file and assign left side variable to right side values. I can read the values from text file properly but can't echo $variable1.
Text file:
variable1="value91";
variable2="value92";
variable3="value93";
variable4="value94";
variable5="value95";
Tried code:
$myfile = fopen("/var/myfile", "r");
while (!feof($myfile)) {
$line = fgets ($myfile);
echo "$line<br/>";
}
fclose ($myfile);
This prints line value and can parse but how can I assign key with value so whenever I use:
Problem:
echo $variable1; which will print "value91"?
I'm certainly fine with static assigning values to variable1, variable2 as well after reading text file if not possible dynamically using file.
Apologies if this has bugs. I haven't written php in a good long while. Something like the following (based on my comment about using Arrays for this):
$myfile = fopen("/var/myfile", "r");
while (!feof($myfile)) {
$line = fgets ($myfile);
$lineA = explode("=", $line);
$data[$lineA[0]]=$lineA[1];;
}
fclose ($myfile);
Using explode to break the key and value of the line into an array.
Then adding to the new $data array the key/value pair from the explode.
Now after you close your file you can get your values out according to the key:
echo $data["variable1"];
Which should echo out value91
You can use the ability to use a string as the target of assignment, so ...
<?php
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );
$lines = file('data.txt', FILE_IGNORE_NEW_LINES);
foreach ( $lines as $line ) {
$data = explode("=", $line);
$varName = $data[0];
$$varName = $data[1];
}
echo $variable1;
Note the assignment is using $$varName, so it uses the first column as the name of the variable.
This outputs-
"value91"

How can I check if a username already exists in a file and also add his points to him?

I intentionally want to use a text file to do this. So I read a text file and I want to check if a username already exists in that text file or not and I want to either add this username to the text file if he doesn't exists or just add the points to him.
My current code:
<?php
$myfile = fopen("test.txt", "r") or die("Unable to open file!");
$file = fread($myfile,filesize("test.txt"));
//echo $file;
fclose($myfile);
//$username = $_REQUEST['username'];
//$points = $_REQUEST['point'];
$username = 'chinmay'; //chinmay is a username this is unique
$points = 200; //if username chinmay not exitst then Insert first time otherwise if username chimay exist then next onwards this point will update everytime in the text file.
$myfileWrite = fopen("test.txt", "a") or die("Unable to open file!");
$txt = $username."|".$points."\n";
fwrite($myfileWrite, $txt);
fclose($myfileWrite);
?>
test.txt:
chinmay|800
john|200
sanjib|480
debasish|541
This is my complete code. My requirement is:
\n is not working when I am using this text inserted in the same line.
How can I check duplicate username?
If I found username then how can I update user points?
I googled last 2 hours but not getting any solution. I have no idea about this problem.
This should work for you:
First use file() to read your file into an array. Then you can use array_map() to loop through each line and explode() it by | as delimiter. After this you can use array_column() to get the username as key for the points as value. Like this:
Array
(
[chinmay] => 1200
[john] => 200
[sanjib] => 480
[debasish] => 541
[chinmayx] => 200
)
With the array you can simply check if the username already exists or not. If not add it to the array and then add the points to it.
After adding the points to the username you can change your data back in the same format and save it with file_put_contents().
Full code:
<?php
$lines = file("test.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$usernames = array_column(array_map(function($v){
return explode("|", $v);
}, $lines), 1, 0);
$username = "chinmayx";
$points = 200;
if(!isset($usernames[$username]))
$usernames[$username] = 0;
$usernames[$username] += $points;
foreach($usernames as $k => $v)
$data[] = "$k|$v" . PHP_EOL;
file_put_contents("test.txt", $data);
?>
EDIT:
If you have PHP under 5.5 just replace:
$usernames = array_column(array_map(function($v){
return explode("|", $v);
}, $lines), 1, 0);
with this:
$lines = array_map(function($v){
return explode("|", $v);
}, $lines);
$usernames = array_combine(
array_map(function($v){
return $v[0];
}, $lines),
array_map(function($v){
return $v[1];
}, $lines)
);
Also if you want to get the TOP 10 users, just rsort() your array and then take an array_slice() of the first 10 elements, e.g.
rsort($usernames);
$topUsers = array_slice($usernames, 0, 10);
print_r($topUsers);
To get the \n working use the PHP_EOL as in another answer
$txt = $username."|".$points.PHP_EOL;
To update the user found in the text file go through following link
how to replace a particular line in a text file using php?
you should use PHP_EOL instead of "\n" which also depends on your OS
$txt = $username."|".$points.PHP_EOL;
for checking userName, just use:
//this works because $file is String because of fread()
if (strpos($file,$username) !== false) {
echo 'user exists';
}
for replacing you'll need regex or use strpos position (which returns position of name in string) and advance the pointer by count($username)+1 and search from there for newline, all this string between that, replace with new points
Try to use preg_match:
$file = fopen("score.txt", "r");
while (!feof($file)) {
preg_match("/^$username|(.*?)$/", $file, $array);
var_dump($array);
}
but I think it's better to use MySQL :)

csv file into array , translation system for a site

I need help to solve this problem:
I have a csv file like this
hello,ciao
goodbye,arrivederci
as you can see I try to create a translation system for a site
now I want this csv file into an array, the resultant array must be the same of $langArray
<?php $langArray = array([it]=>array([hello]=>ciao,[goodbye]=>arrivederci)); ?>
I already have a solution using a Json file to have an array like this, and is most usefull that a csv file and I can use translation system also with javascript. but I want to know the way to do that with a csv file thank you
For reading a CSV file you should use fopen and fgetcsv, or for the short version str_getcsv (needs current PHP or compat library):
$csv = array_map("str_getcsv", file("it.csv"));
Then building the associative map requires a manual loop:
foreach ($csv as $line)
$translate["it"][ $line[0] ] = $line[1];
You could use explode to split your data once for the new line, then once for the comma, and fill an array with it.
<?php
$translations = array();
$data = 'hello,ciao
goodbye,arrivederci';
$words = explode("\n", $data);
foreach($words as $w) {
$parts = explode(',', $w);
$translations[$parts[0]] = $parts[1];
}
print_r($translations);
?>
http://codepad.viper-7.com/gCKoI9
<?php
$languageArray = ARRAY();
$my_csv_it = 'hello,ciao goodbye,arrivederci';
$tmp_array_it = explode(' ', $my_csv_it);
foreach ($tmp_array_it AS $text) {
$pairs = explode(',',$text);
$languageArray['it'][$pairs[0]] = $pairs[1];
}
print_r ($languageArray);
?>

problem with PHP reading CSV files

I'm trying to read data from a.csv file to ouput it on a webpage as text.
It's the first time I'm doing this and I've run into a nasty little problem.
My .csv file(which gets openened by Excel by default), has multiple rows and I read the entire thing as one long string.
like this:
$contents = file_get_contents("files/data.csv");
In this example file I made, there are 2 lines.
Paul Blueberryroad
85 us Flashlight,Bag November 20,
2008, 4:39 pm
Hellen Blueberryroad
85 us lens13mm,Flashlight,Bag,ExtraBatteries November
20, 2008, 16:41:32
But the string read by PHP is this:
Paul;Blueberryroad 85;us;Flashlight,Bag;November 20, 2008, 4:39 pmHellen;Blueberryroad 85;us;lens13mm,Flashlight,Bag,ExtraBatteries;November 20, 2008, 16:41:32
I'm splitting this with:
list($name[], $street[], $country[], $accessories[], $orderdate[]) = split(";",$contents);
What I want is for $name[] to contain "Paul" and "Hellen" as its contents. And the other arrays to receive the values of their respective columns.
Instead I get only Paul and the content of $orderdate[] is
November 20, 2008, 4:39 pmHellen
So all the rows are concatenated. Can someone show me how i can achieve what I need?
EDIT: solution found, just one werid thing remaining:
I've solved it now by using this piece of code:
$fo = fopen("files/users.csv", "rb+");
while(!feof($fo)) {
$contents[] = fgetcsv($fo,0,';');
}
fclose($fo);
For some reason, allthough my CSV file only has 2 rows, it returns 2 arrays and 1 boolean. The first 2 are my data arrays and the boolean is 0.
You are better off using fgetcsv() which is aware of CSV file structure and has designated options for handling CSV files. Alternatively, you can use str_getcsv() on the contents of the file instead.
The file() function reads a file in an array, every line is an entry of the array.
So you can do something like:
$rows = array();
$name = array();
$street = array();
$country = array();
$rows = file("file.csv");
foreach($rows as $r) {
$data = explode(";", $r);
$name[] = $data[0];
$street[] = $data[1];
$country[] = $data[2];
}
I've solved it now by using this piece of code:
$fo = fopen("files/users.csv", "rb+");
while(!feof($fo)) {
$contents[] = fgetcsv($fo,0,';');
}
fclose($fo);
For some reason, allthough my CSV file only has 2 rows, it returns 2 arrays and 1 boolean. The first 2 are my data arrays and the boolean is 0.
The remark about fgetcsv is correct.
I will still answer your question, for educational purpose. First thing, I don't understand the difference between your data (with comas) and the "string read by PHP" (it substitutes some spaces with semi-colon, but not all?).
PS.: I looked at the source code of your message, it looks like an odd mix of TSV (tabs) and CSV (coma).
Beside, if you want to go this way, you need to split first the file in lines, then the lines in fields.
The best way is of course fgetcsv() as pointed out.
$f = fopen ('test.csv', 'r');
while (false !== $data = fgetcsv($f, 0, ';'))
$arr[] = $data;
fclose($f);
But if you have the contents in a variable and want to split it, and str_getcsv is unavailable you can use this:
function str_split_csv($text, $seperator = ';') {
$regex = '#' . preg_quote($seperator) . '|\v#';
preg_match('|^.*$|m', $text, $firstline);
$chunks = substr_count($firstline[0], $seperator) + 1;
$split = array_chunk(preg_split($regex, $text), $chunks);
$c = count($split) - 1;
if (isset($split[$c]) && ((count($split[$c]) < $chunks) || (($chunks == 1) && ($split[$c][0] == ''))))
unset($split[$c]);
return $split;
}

Categories