delimited txt file to array? then update mysql PHP - php

How'd I go about reading a tab delimited .txt file and then coding it so it puts each column of data(that is seperated with a tab) into a php variable.
for example....
505050 somedata moredata
and then, writing these variables to
$id
$somedata
$moredata
I read into fgetcsv and making an array although it seemed to make the whole line an array i need to split it into variables so that i can write it to individual columns in the MySQL database,
Can anyone give me any pointers?
Thanks so much...

A combination of fgetcsv() and list() will be the most efficient way to split this into named variables:
list($id, $somedata, $moredata) = fgetcsv($fp, 0, "\t");
However, you do not need to have them as named variables in order to insert them in MySQL, you can just use the raw array returned by fgetcsv():
$row = fgetcsv($fp, 0, "\t");
$query = "
INSERT INTO `tablename`
(`id`, `somedata`, `moredata`)
VALUES
('{$row[0]}', '{$row[1]}', '{$row[2]}')
";
Don't forget to escape the data before using it in a query ;-)

explode() will split a string. Try this:
list($id, $somedata, $moredata) = explode("\t", $string);
Where $string is the string you want to split. For more info about explode() and list(), just look up on php.net.

You can use explode():
http://php.net/manual/en/function.explode.php

Related

PHP: Write comma to csv file

I've got a form which submits data to a csv file.
When a user inputs a comma to a field, it destroys my csv structure.
I want to convert inputted commas so that they can get displayed as a character.
I tried this:
$_POST["field"] = str_replace(",", "','", $_POST["field"]);
Use html encoding for instant relief , but still my recommendation to use phpExcel
$comma="&#44";
$_POST["field"] = str_replace(",", $comma, $_POST["field"]);
You can use fputcsv() to write, and fgetcsv() to read the file, it automatically converts your string.
A simple example for writing the data:
$csv = fopen('file.csv', 'w');
$array = array($csv);
fputcsv($csv, $array);
And reading the data:
$csv = fopen('file.csv','r');
print_r(fgetcsv($csv));
Probably not the best answer, but it does work.
You could replace the comma with a random string when inputting to the CSV as below:
$commastring = str_replace(",", "/zwdz/", $tempstring);
and then when you need to output the comma somewhere on your website (if a database website) you can do the opposite str_replace
You can escape coma like this:
$_POST["field"] = str_replace(",", "\,", $_POST["field"]);
Or you can put string in quotes
$_POST["field"] = "'".$_POST["field"]."'";

reading txt file using php , storing content to database

I am having one txt file, with data simillar to below. I need to read the file and store the content in database using php, I am trying to explode the line and read it into array, but 7th column itself contains "," so not able to explode it properly using ",". Any help on this, how it can be done.
"MN", 2215," 309 ","4002 ",10,"10463","VAN TULL, GORDON ",000003120," ",1, 2, 4, "Y"
"MN", 2215," 309 ","4002 ",10,"10463","RODRIGUEZ, RANDY ",000003120," ",1, 2, 4, "Y"
I am trying following
$handle = fopen($filename, "r")
1) $line = fgetcsv($handle,",")
this is not working as column 7th itself have "," in its value.
2)
$Line = fgets($handle);
$data=explode(",",$Line);
if count($data)>13
// concatenating col 6 and 7
You didn't mention how you're trying to parse the csv, but I'm guessing you're just splitting it around the comma. Instead, try fgetcsv.
There are couple of ways at least
SIMPLE way is to replace all necessary commas with some special character and explode
bit programmatic - use regex
$contents = file_get_contents(__dir__.'/sample.txt');
$rows = explode(PHP_EOL, $contents);
foreach($rows as $row){
$cols = preg_split('/,(?=(?:[^"]|"[^"]*")*$)/', $row);
// do what you want to do with cols, which is an array of columns
}

Using php's explode function on fractions

I'm using a simple explode operation to use array values for inserting records to mysql database.
The code i use is:
// for loop above
$fieldsArr = explode(',', $field_names);
where $field_names is a string like :
'1_gps_update_coordinates','1' // prints out just fine
'1_meter_conf_holiday1_end','2099-01-01' // also fine
but
'1_electricity_unit_price','0,100' gives problem.
How can I overcome this? Any tip is appricated.
Ps $field_names values comes directly from database so I cannot really write an if statement.
if you can't change the input data, you can do this:
change the delimiter from comma to semicolon with str_replace function
$field_name = str_replace("','", "';'", $field_name)
then you can explode by semicolon
$fieldsArr = explode(';', $field_names);
You need to insert float using english number formatting
0.1
Instead of european 0,1
Use number_formatting() or simply str_replace(',', '.', $val);

How to make a list to keyword list with PHP

I want to do something with PHP .
I have this list of names :
first
second
third
forth
Now i want to have this :
first,second,third,forth
How can this happen with a little PHP code ?
Assuming that you have those in array
$arr=array('first','second');
$str=implode(",",$arr);
EDIT(assuming each names are on the new line, i will replace \n with ,)
$str=file_get_contents("filename.txt");
$newstr=str_replace("\n",',',$str);
$newstr=trim($newstr, ",");//to remove the last comma
echo $newstr;
i think you text tag based on new line, so try this
first
second
third
forth
$arr = explode("\n", $txt);
echo implode(",",$arr);
every new line consider as a array value.
This is really basic PHP, I can't believe it isn't covered in most tutorials.
$array = file("filename", FILE_IGNORE_NEW_LINES);
$string = implode(',', $array);
I think you're looking for explode, like so http://us2.php.net/explode
array explode ( string $delimiter , string $string [, int $limit ] )
You want to set $delimiter to ' ', $string can be a copy -> paste of your text.txt content.
The best thing to do would be: take the text.txt content and use search-replace to remove new lines and add spaces (or commas), so you go from
ron
john
kahn
to ron, john, kahn, at which point you can import an array for use in php.

In PHP, Removing first element in CSV String

I'm simply looking to take the first csv out of a string, using PHP. Here are a few examples:
"Sea Bass, Floured Or Breaded, Fried" => "Floured Or Breaded, Fried"
"Tuna, Fresh, Baked Or Broiled" => "Fresh, Baked Or Broiled"
"Croaker, Breaded Or Battered, Baked" => "Breaded Or Battered, Baked"
And so on...
Thank you.
You can try this:
$csvArray = explode(",", $csv);
array_shift($csvArray);
$newCsv = implode(",", $csvArray);
I suggest using str_getcsv or something similar that parses csv, this will take into account any quotation marks and commas in the CSV string. after that you can just array_shift

Categories