create PHP array using fopen with append [duplicate] - php

This question already has answers here:
PHP Array saved to Text file
(4 answers)
Writing Array to File in php And getting the data
(5 answers)
How do I store an array in a file to access as an array later with PHP?
(8 answers)
Closed 3 months ago.
I am having trouble figuring out how to write to a file using fopen "a" append mode.
the file itself is a simple PHP array:
$array = array(
"entry1" => "blah blah",
"entry2" => "forbarbaz",
);
simple enough. So using fopen with the 2nd arg set to "a" should allow me to append the file using fputs.... the problem is the opening and closing lines, ie $array = array( and );
so now the file should look like this:
"entry1" => "blah blah",
"entry2" => "forbarbaz",
how would I rebuild this data into a working PHP array assuming it is just a txt file with a list of entries without the opening and closing lines? Sorry if this is not clear, its a little complicated. No I am not going to store these values in a DB, I need the speed advantage by holding these particular values in a file array.
So the questions really is how would i go about constructing the usable PHP array from a txt file with a line by line list like this?
To clarify:
how do i pull in a txt file with lines like this:
"entry1" => "blah blah",
"entry2" => "forbarbaz",
and have a workable $php_array()????

Try this.
File format (at the beginning of work with it):
<?php
$array = array();
Now it's correct php-file.
Then simply add new rows like as follows:
$f = fopen('myarray.php', 'a');
fputs($f, PHP_EOL.'$array["entry1"] = "value1";');
fclose($f);
And use it by simply include('myarray.php');

Why not json_encode the array when you store it in the file and then json_decode the JSON into an array when you extract it from the file?
json_encode
json_decode

Maybe you're looking for the fseek function: http://se.php.net/fseek
When opening a file in r+ mode, the file pointer is at the beginning of the file. Sounds like you want to place it at the end of the file minus a few bytes, then write your new data.

Untested. Try this:
$data = file_get_contents('./data.txt', true);
$array = eval("array(".$data.")");

Related

Write object in JSON file [duplicate]

This question already has answers here:
How to add to JSON array in .json file
(2 answers)
Closed last year.
I have a project based on PHP with OOP structure. When I register a user, it creates a user object and writes that object to json file. The problem is, in this way each time I create a user, the json object stores separately in the file.(shown in the image)
So when I re-read this json file using json_decode() function, it doesn't read anything. I've used the following method to check the file reading.
$data = json_decode(file_get_contents($file), true);
$f = fopen("log", 'a');
fwrite($f, $data);
So how can I append the json objects as list of arrays(upon registering a single user) or read all the entries from the file?
Most of the solutions that I have seen are predefined arrays, but in my case the objects are being created at runtime and only one at a time.
I agree with #Konstantinos Gounaris. The json file is in wrong format. That's why the json_decode function returned nothing. Always use json_encode while writing the json file and write it in one flow. If you want to append to the file, just read the contents, decode it and write it again. Don't append to the file, because it will break the json format.
#Note: Saving confidential information to the file is wrong practice, which leads to security issues.
It is a better practice to use databases to store data(they are more secure than files). However. The first thing that i can see that is wrong is that you are decoding the json file into an php array and then you are writing this array into a file, this results into wrong Json format.
Bellow is an example of how you should do it:
$data_to_import = ['name'=>'John','surname'=>'Doe'];
$data_array = json_decode(file_get_contents($file), true);
array_push($data_array, $data_to_import);
$f = fopen("log", 'a');
fwrite($f, json_encode($data_array));

Parsing a CSV file in PHP using regular expressions [duplicate]

This question already has answers here:
Regular expression for parsing CSV in PHP
(6 answers)
Closed 8 years ago.
I have a text file (similar to CSV concept) to parse and load into different columns.
I receive it from an external application I can't modify.
It uses ";" as field separator but unfortunatly we can have the same char also inside some content.
Here a little sample:
Code;Name;Address;E_mail;Contact name
000001;FUTURAMA SNC;VIA BARBAPAPA, 1;info#gmail.com;matteo futuro;
000006;FERRANTIBUS SRL;VIA TOPOLINO, 1;amministrazione#gmail.com;nicola ferri;
000008;MORMORO SPA;VIA CICCETTI, 30;"cri#mormoro.it; rossi#mormoro.it";panebianco gianpietro;
we use this code to parse the file
$file = fopen("C:\\wamp\\www\\testcsv\\customers.csv","r");
$result ="";
$i=0;
while(! feof($file))
{
$result[$i++]= fgets($file);
}
for($j=1;$j<count($result);$j++){
$tempData = preg_split("/[;]/",$result[$j]);
print_r( $tempData );
}
as you can see, in the last line of the sample file, we have ";" char inside email field.... so it is read as another column separator and in the third record the email field is splitted as 2 column, with the result I have an additional column.
Is there any way, using regular expression to skip ; char if it is inside the "" chars?
Thanks in advance for the help
You should not use regexpr to parse CSV files.
Use native PHP function http://php.net/manual/en/function.fgetcsv.php
This will solve your problem.

Replace strings in a file from an array in PHP

This is a tricky one...I am trying to replace some strings in a file that i hold in array.
Because there are a lot of files...i've been trying to find the fastest way possible.
I tried this (which worked) but it was slow.
First parsed all the files and got an array of the values i want to
change (lets say 500).
Then I wrote a foreach loop to parse through the files one by one.
Then inside that, another foreach loop to go through the values one by one
preg_replacing the file for any occurrences of the array value.
This takes forever though cause not all files need to be parsed with 500 array elements.
So i am changing the code now like this:
Parse every file and make an array of the values i want to replace.
Search the file again for all the occurrences for each array value and replace it.
Save the file
I think this will be much faster that the old way...The problem i am having though now is with the read/write loop, and the array loop...
I want to do this as fast as possible...cause there will be a lot of files to parse and some have 100+ values.
So far i got this in a function.
function openFileSearchAndReplace($file)
{
$holdcontents = file_get_contents($file);
$newarray = makeArrayOfValuesToReplace($holdcontents);
foreach ($newarray as $key => $value) {
$replaceWith = getNewValueFor($value);
$holdcontent = preg_replace('/\\b'.$value.'\\b/', $replaceWith, $holdcontents);
}
file_put_contents($file, $holdcontent, LOCK_EX); //Save and close
}
Now, this doesnt work...it just changes 1 value only because i have file_put_contents and file_get_contents outside of the foreach. (Not to mention that it replaces values that it shouldnt replace. Probably cause the read/write are outside of the loop.) I have to put them inside to work..but thats gonna be slow..cause it take 3-4seconds per file to do the change since there are a lot of elements in the array.
How can i "Open the file", "Read it", "Change ALL values first", "Then save close the file", so i can move to the next.
EDIT:
Maybe i am not explaining it well i dont know...or is this too complicated....I have to parse the array of values...there is no way i can avoid that...but instead of (In every loop), i open the file search and replace 1 value, close the file.....I want to do this:
Open the file, get the content in an array or string or whatever. For all the values i have keep replacing the text with the equivalent value, and when all the values are done...that array or string write to the file. So i am only opening/closing the file once. Instead of waiting for php to read/write/close all the time.
-Thanks
How about just using str_replace(mixed $search , mixed $replace , mixed $subject)?
You can have an array of search strings which will be replaced by their corresponding item in the replace array and as the PHP manual says:
If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of preg_replace().
Also just close the file and reopen it with mode 'w'. File will be truncated to 0 length
Added Edit
$fileContents = file_get_contents("theFile");
$search = array('apples', 'oranges');
$replace = array('pears', 'lemons');
$newContents = str_replace($search, $replace, $fileContents);
$handle = fopen("theFile","w");
fwrite($handle, $newContents);
fclose($handle);
That's it your file has all the old strings replaced with new ones.
There is no solution to the problem. file_get_contents and file_put_contents simply doesnt work like that.
I appreciate everyone's attention to the problem.

Use PHP to edit a specific line in a file

I have a php file that has an array in it. I'd like to be able to add an item to that array using a simple form.
Here is an example similar to my array:
$list = array("BA0UKSF","BA9IHHE","BAC8GMB","BAC8HMC","BAC8HMC","BAC8HMC","BACI60T","BAEIDFD","BAEIEFE","BAEIEFE","BAMB0","BAOUKSE","BAOUKSF","BAPQADL","BAPQADM","BUNDLE","CN3ICDC","CN3ICDCA","CN7IZDPA","CN8ID42","CN8ID72","CNECBCBA");
I'd like to add the new item to the array someplace either at the beginning or end of the array list.
I know how to pass the forms data to php but what I dont know is how to get php to open this file, locate the array and add something to it.
I'd just store your array data in JSON format what makes it very easy to operate on the array.
Reading array:
$list = json_decode(file_get_contents($file));
Saving array:
file_put_contents($file, json_encode($list));
Reasons:
It is very bad practice to patch PHP code. (difficult to maintain; will possibly stop to work as you change the code in the file etc.)
If your input you add to $list is user-input and not 100% validated, it may be malicious code in it...
You can parse the text file line by line and locate the array first. And then, you can simply use:
array_push() -- if you want to add elements to the end of the array
array_unshift() - if you want to add elements to the beginning of the array
Examples:
array_push($list, "CN7IZDPA"); //adding to the end
array_unshift($list, "CN7IZDPA"); //adding to the beginning
But reading your array definition from a text file seems like a bad idea. You really should use a database as it makes managing the stuff easier.
Hope this helps!

php - delete words from array by matching external text file

I have an array and an external file, both contains lots of words. I want to match strings in the array with the entire external file. Then if there are identical words, I want to delete the word from the array.
Much shorten example:
$words = {"apple", "orange", "banana", "grape", "peach"}
The external text file is a pure list of words
apple
banana
melon
...
I'd like to delete the words that are in the external file, and finally get this.
$words = {"orange", "grape", "peach"}
Should I call the external file, slice every line, then save them to another array? Then compare with the source array?
What is the most effective way to compare the array and a text file?
I'd appreciate your wisdom!
You could use array_diff.(file to get an array from file.)
$result = array_diff($words, file('path_to_file', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
PS: If your external text file is very big, and you don't want to load it to memory at one time, you could read it line by line, and check it whether it exists in the array.

Categories