Reading specific CSV value in PHP - php

I have the following CSV file:
08-0018421032;00-0018151831;G-20009429-0;G-20009429-0;0374048-0
27-001842101232;10-0018151831;G-30009429-0;G-50009429-0;7374048-0
36-0018421033232;20-0018151831;G-40009429-0;G-60009429-0;8374048-0
As you can see the separator is the ; symbol.
I then send this info to php via a jquery plugin which works perfect since I can read the file in PHP. The following code grabs the CSV file (Which is the $csvfile variable) and I can see the lines in it:
$file = fopen("upload/$csvfile", "r");
while (!feof($file) ) {
$line = fgetcsv($file, 1024,';');
print $line[0].'<br/>';
}
fclose($file);
What I need is to be able to select not only the line but on the value in it. To go to a specific value, for example in the first line the 3rd value would be G-20009429-0 and I would assign this to a php variable to be used later on.
Right now I have no idea how to grab a specific value in a line and also when I print the $line[0] it shows the values in a vertical order instead of a horizontal order. What I mean with this is that it shows the following output:
00-0018151831
10-0018151831
20-0018151831
Instead of showing me like this:
08-0018421032;00-0018151831;G-20009429-0;G-20009429-0;0374048-0
Maybe is the sleep but am stuck here. Just to repeat, the csv file is read by Php correctly since I can do a print_r on it and it shows all the lines in it. The thing is how to manipulate the information after I have the csv and how to grab a specific value in a specific line. Thank you.

$line is an array containing every element from that row. $line[0] is the first element of the row, $line[1] the second element and so on. Try var_dump($line). What you're doing is you output every first element of every row.
If you want to output every element in one line, just concatenate the array again:
echo join(';', $line);
But then that's missing the point of fgetcsv, which is specifically helpfully separating those elements into an array for you so you can work with them.

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.

Read, sort and split text file into blocks

I am trying to re-activate my php knowledge for the following task:
I have a larger textfile containing unsorted lines of comma separated informations, each value enclosed by a '"'.
Each line can be understood as a single dataset, the first value of the line tells me in which table the row belongs.
Now I need to read the file, sort the lines (so that the lines belonging to the same table are together), detect the different blocks and save them in seperate text files. After that, I can do a fast import into a mysql database using load data from infile..
So, I can open the file and sort the lines via this:
<?php
$lines = file("importfile_unsorted.txt");
natsort($lines);
file_put_contents("importfile_sorted.txt", implode($lines));
?>
This works. But now I get stucked. importfile_sorted.txt looks like this:
"AV1","0","0","0","0","0","0","0","0","0","0","0:0","0:0","0:0"
"AV2","0","0","0","0","0","0","0","0","0","0","0:0","0:0","0:0"
.... [this would be the first block, all these lines should be saved in "av.txt"
In the next line the new block "F" begins with several lines:
"F1","D","D","Deutsch",,,"0","W"
"F4","E","E","Englisch",,,"0","W"
"F7","K","K","Kath.Religionslehre",,,"0","W"
"F8","Ev","Ev","Evang.Religionslehre",,,"0","W"
"F9","Eth","Eth","Ethik",,,"0","W"
... [save all these lines beginning with Fxx into file f.txt and go to the next blocks]
"G1","PhL","PÜG"
"G2","ChL","ChÜ"
..
"K1","5a","5a",,"304","Ma","Wei","0","16","16","5",,,,,"1","1","0",,"0","0","0","0"
"K2","5b","5b",,"303","Wo","Hm","0","32","16","5",,,,,"1","1","0",,"0","0","0","0"
"K3","5c","5c",,"302","Gr","Ro","0","32","16","5",,,,,"1","1","0",,"0","0","0","0"
... and so on. Later, there are blocks with a fixed first column like this:
"PL","Di 1","Ba","Q12","Inf1","CoR1"
"PL","Di 1","Bb","Q12","F","Ü2"
"PL","Di 1","Eg","Q12","L","M23"
...
and
"PLS","Di 1","Am"," frei "
"PLS","Di 1","Bad"," ----"
"PLS","Di 1","Bk"," frei "
...
followed by several other blocks (L1... L97, M, R1... R40, U1... U560).
I know all possible "identifiers" (AVx, Fx, Gx, .. PL, PLS..) of the blocks, but it is also possible that a block is omitted and the input file does not a single line of it at all.
The input file contains about 4000 lines all together, so performance should not be too low (although it's not time-critical, the import is done maybe 10 times a year..).
So, is there a way of getting this done in a "smart" and fast way or should I read the input file line by line, detect and remember the first value, add the current line to a result string and loop until a new first value occurs?
Thanks for your help!
Heiko
Use the built in CSV parser, don't split this manually
http://php.net/manual/en/function.str-getcsv.php

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!

How to add an array into a comma delimited text file without deleting previous array values

I'm trying to make a form where the user can add their own 'questions + answers' to the quiz.
I loaded the original questions from a text file. The added questions will then be processed by process_editadd.php
<?php
session_start();
$file = fopen('data.txt', 'r');
$array=$_SESSION['questions_array'];
//make array out of values
$q=array($_POST['question'],$_POST['one'],$_POST['two'],$_POST['three'],$_POST['four']);
//add to file
$file=fopen("data.txt","w+");
fwrite($file, implode(',', $q)).
header('Location:module.php');
?>
The array adds onto the text file, but the problem is that it replaces the whole thing. I don't want the questions to replace the previous ones, I just want them added. Do you guys know what's wrong with the code?
Note: I'm not allowed using mySQL or Javascript
You could switch to using an actual database and make your life a lot easier... Failing that, look into fputcsv and fgetcsv to make it a slightly less tedious problem.
Your implode version right now is also vulnerable to CSV injection... you don't handle the case where any of the text you're writing MIGHT contain a comma. If it does, you'll suddenly find you'll have extra "columns" when you read the data back in later on.

Categories