Excel to PHP array, possible and how? - php

I have a big excel file that looks like this:
I would like to put each row into an array.
Is this possible to access the first row's order id like this?
$result[0][2] // returns 7432
Assuming the actual first row that gives prefix for the columns' name is not present.
How could I do that?

I recommended to use PHPEXCEL library
https://github.com/PHPOffice/PHPExcel
you can see an example
Update:
Now the alternative to this library is phpspreadsheet

Save the spreadsheet as a CSV, then use PHP's built-in CSV functions. See the sample code here:
http://php.net/manual/en/function.fgetcsv.php

May be my answer is too simple (for one time work only), but I use the CONCATENATE "Function" in excell.
The last cell on each row will have concatenation function, like this:
=CONCATENATE("['";A2;"'=>['data1' => '";B2;"', 'data2' => '";C2;"'],")
where:
column "A" is ID of something;
column "B" is first characteristic;
column "C" is second characteristic;
etc.
Then just copy and paste function results to Your script or config file, and do not forget the first and the last bracket.

This works for me:
$content = file_get_contents($your_file_path);
$lines = array_map("rtrim", explode("\n", $content));

Since the PHPExcel library deprecated they've released "PhpSpreadsheet"
This will help PhpSpreadsheet

Related

Reading a text file with specific code tag information in php

I would like to read a file, generally a text file, each record is starting with a with a specific code (filed name) in the line and ended by another specific code for a complete record. Each specific code is delimited by character ^ as its value in php into dump into sql database.
text file e.g.
001^UK2000009
008^S54/01/R/M/X,
009^Male
110^text1
200^text2
001^UK2000008
008^S54/012/R/M/X
009^Female
110^text1a
200^text2a
and so on...
This is similar to php constructor File_MARC
thanks in advance
First you have to read a file with file methods in php and than you can get a specific column name and it's value by below way
First read a single line from a file and than use a explode method to break that line into different elements with space delimitation.
$columns = explode(' ', $line_variable);
After generating columns I can see that each key values are delimited by ^ (cap) symbol so for that also we can use the explode method.
$newColumn =[];
foreach($columns as $column){
$splited = explode('^', $column);
$newColumn[][$splited[0]] = $splited[1];
}
print_r($newColumn);
This is just to give you an idea that how you can achieve your task but rest is completely dependent on you.

Change entry in a CSV file with PHP

I have a CSV file with three columns:
Mary,150203_15:29:12,150203_16:10:12
John,150203_15:29:17,pending
Peter,150203_15:29:35,150203_15:49:35
Olga,150203_15:30:43,pending
...
..
.
Mary,150204_15:42:14,pending
Peter,150204_20:42:14,pending
Because there are many entries on that file all I want to do is
find the latest entry according to the Username and change the last value (from pending to date()).
In the example above lets say I want to change the latest Mary entry in the 3rd column from pending to date. Then replace the updated CSV file with the current one.
Any ideas on how to approach that?
Thank you
You can work with the file as one huge string and do a string replacement.
$data = file_get_contents('your_file.csv');
$data = str_replace('Joe,150203_16:21:43,pending','Joe,15203_16:21:43,15204_15:23:43',$data);
file_put_contents('your_file.csv', $data);
The comments below raise a concern of finding out what the latest date is for a name. That is also rather simple to do. Assuming you've loaded $data in, as above...
$matches = array(); // Just to point out that this is an array
preg_match_all("/Joe,(.*),/", $data, $matches);
Now, $matches[1] contains all the dates for Joe. Did you ONLY want the ones that are pending? No problem...
preg_match_all("/Joe,(.*),pending/", $data, $matches);
Now, $matches[1] only contains the pending dates. Which is the most recent?
rsort($mathes[1]);
Now, $matches[1][0] is the most recent date. So, you can do:
$data = str_replace('Joe,'.$matches[1][0].',pending','Joe,'.$matches[1][0].',15204_15:23:43',$data);
Is this the absolute most efficient way to do this? No. Is it impossibly hard? No. You should look into using a proper database, but it is possible to use csv files.
If moving the data to a DB is not a solution in your case, you could do the following:
Read the CSV file into PHP via fgetcsv(), line by line, into an
array
Sort the array based on your criteria and get the latest entry
Update the entry
Write the entries back into the file via fputcsv()
I actually found a much simpler solution to this. Was the simplest one I could come up with.
$line = $_SESSION[username].",".$_SESSION[LOGIN_TIME].",".'pending'."\r\n";
$newline = $_SESSION[username].","$_SESSION[LOGIN_TIME].",".date("ymd_H:i:s"). "\r\n";
$data = file_get_contents('login.log');
$data = str_replace($line,$newline,$data);
file_put_contents('login.log', $data);
So there is no need for scanning for the latest entry. I just store the previous entry values and replace them with the new ones.
Thank you kainaw and BigScar

PHP Creating CSV not working as expected

i'm trying to create a CSV using this solution:
Creating csv file with php
Something is wrong, i keep getting data stuffed into one cell like this:
each value should be in an own cell .. any ideas what's wrong?
seems like the csv uses the wrong delimiter.
thanks
I finally found the solution: seems like it doesn't work for the German version of Excel,
all I had to do is changing the delimiter to a semi-colon like this:
fputcsv($fp, $val, ";");

how to manipulate csv from code (cron)? php...? Example: insert+delete column values...

The case is the following:
i have a csv with some columns...
1) i have to automatically insert an empty column between H and I, so other columns just have to move to the next place I -> J ... J -> K and so on...
2) O column values have to become the new I column values, and then delete every value contained inside the "old" O
3) save the csv
Thanks for your help
You have to read the file into memory using fgetcsv(). Then you can do your magic by manipulating the arrays, using for example array_splice(). Finally, you write the "CSV array" back to disk using fputcsv().
you can use the Spl library, to see an example: http://www.php.net/manual/en/splfileobject.setcsvcontrol.php

php text file news updates

I am trying to make a news feed type thing in php.
I have a text file - news.txt and a php file index.php.
I have done the surrounding code and opening/closing the text file. Now I am stuck how to insert the new news item $newsnew to the top of the news.txt file and how to delete the old bottom news file in the news.txt file.
Is there any way to do this without deleting the whole file and writing it all again?
EDIT: Each news item is just a small string, say 500 characters, a single line.
Use a database.
If you really must use text files, use a different file for every news-item and name them sequentially like:
news001.txt
news002.txt
etc.
Then you can just add and delete files, read the directory and display what´s there.
Use the file() function to import the items in news.txt as an array, and use array_unshift() to add the new first item, and array_pop() to remove the last item. Join the array back into a single string and write it to news.txt:
$items = file('news.txt');
array_unshift($items, 'New item 1');
array_pop($items);
$newstext = implode(PHP_EOL, $items);
// write $newstext to the external file
If this is a XML file you could read it, parse it and delete the last child in the DOM. But if you have all your data in a DB it could be much easier to rewrite the file every time.
EDIT: after your edit: yes, you can do it like this:
write your new line to a new file
read the old file line by line and write it to the new one
skip the last line (detected by counting or EOF)
delete the old file and rename the new
No, there is not. But you might consider storing the messages in revers order. That way you only need to append to news.txt when new news arrive.
You are not going to be able to prepend to the beginning of the file without writing the whole thing out again. You could append to the end of it with the "a" mode flag to fopen(), but still to delete the oldest item you'll need to write out the entire file again.
Really, a database is solution here instead of a single text file.
There are many ways you can do it using the flat text file, but I'm not really sure it it's worth it. You can use some lightweight structured file or embedded database. For example SQLite, which would store it in normal file, no additional setup needed.

Categories