Reading CSV file data in PHP - php

I'm trying to create a page which pulls infoprmation from a CSV file, using PHP.
It should then populate a product list with the information.
This is the CSV file:
The code I have is as follows:
$file = file('data-example.csv');
$line = array("name", "id","price", "description");
foreach($file as $line) {
$csv = explode('//',$line);
$item = $csv;
print_r($item);
This is currently printing out the whole of the array. I'd like to know how I can access the individual nodes on the array, so that I could include them as variables within an HTML table.
Thanks
Ali
To amplify, and respond to the replies (thanks!):
This is the amended code, using fgetcsv:
if (($handle = fopen("data.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
echo($data[1][1]);
}
fclose($handle);
}
This seems to work, but returns the column contents. This is the data (data.csv):
"Dandelion","30","13.99","Dandelion 30 "
"Daisy","40","20.99","Daisy 40 "
"Cress","27","10.99","Cress 27 "
"Coral","17","6.99","Coral 17 ",
"Honeysuckle","40","17.99","Honeysuckle 40 "
"Rose","27","9.99","Rose 27"
"
(there's a new line at dandelion, Daisy,Cress,Coral,Honeysuckle and Rose)
When I try echo($data[1]); it gets the whole column as described, i.e 30 40 27 17 40 27 but echo($data[1][1]); returns "342142", and echo($data[1][1][1]); creates an error.
I don't understand it as this is an array?
Thanks
Ali

You should use native php functions to read csv files, such as str_getcsv
Something like:
$Data = str_getcsv($CsvString, "\n"); //parse the rows
foreach($Data as &$Row){
$Row = str_getcsv($Row, ";"); //parse the items in rows
}
Alternatively you can use fgetcsv that parses the line it reads for fields in CSV format and returns an array containing the fields read, i.e.:
<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>

Related

PHP fgetcsv with not valid CSV file

I have a CSV file with content:
Центральный;Московская область;117036;PC;JEEP;GRAND CHEROKEE;ДЖИП ГРАНД ЧЕРОКИ;В;01.01.0001;08.05.2014;2004;1J8G2Е8N94У161064;-;1J8G2Е8N94У161064;-;94;2;227;4701;1;1;29;2495;2073;ФИЗ ЛИЦО;-;АКАДЕМИЧЕСКИЙ (ЮЗАО) Р-Н;-;-;-
Центральный;Московская область;117036;PC;VAZ;LARGUS;ЛАДА ЛАРГУС FS015L;В;01.01.0001;08.05.2014;2014;ХТАFS015LЕ0811430;UА46515;ХТАFS015LЕ0811430;-;11;1;84;1598;1;1;09;2010;1260;"АЗИЯ МАТЕРИАЛ ХЭНДЛИНГ ООО;7728814946;АКАДЕМИЧЕСКИЙ (ЮЗАО) Р-Н;-;КРЖИЖАНОВСКОГО;2|21
Центральный;Московская область;117208;PC;TOYOTA;LANDCRUISER;ТОЙОТА ЛЕНД КРУЗЕР ПРАДО;В;01.01.0001;08.05.2014;2001;JТЕВN99J100077420;1122027;JТЕВN99J100077420;JТЕВN99J100077420;94;2;178;3378;1;1;21;2680;1900;ФИЗ ЛИЦО;-;ЧЕРТАНОВО СЕВЕРНОЕ (ЮАО) Р-Н;-;-;-
I tried import this CSV to SQL DB with this while loop:
while (($csv_data = fgetcsv($csv_file, 10000, ';', '"')) !== false) {
//some stuff
}
In this CSV file I have 3 records, but in SQL I see only 2. Problem in this line:
;1260;"АЗИЯ МАТЕРИАЛ ХЭНДЛИНГ ООО;7728814946;
Problen in extra character " before АЗИЯ. How I can correctly parse this CSV file? File is more then 200 Mb.
===== EDIT =======
Okay, obviously your CSV gets not parsed right I used different data and thought CSV is CSV and that example worked just as fine idk. Now it works with your data. Only problem is your ", this is causing problems
(I replaced your first element because I don't speak Russian and I cannot see differences in words)
$file_data = array_filter(explode("\n", file_get_contents("data.csv")));
$data = array();
foreach ($file_data as $key => $row) {
$data[] = str_getcsv($row, ';', '', "\\");
}
print_r($data);
===== OLD MESSAGE =======
I tried this PHP example and it worked just as fine.
/*
$row = 1;
if (($handle = fopen("data.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in roe $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
*/

PHP changing the index of multidimentional array to value of variable

Pretty new to PHP. I have a csv feed that i am trying to display every line of in the right place. The feed is loaded into a multidimentional array and I can echo out specific places like this.
echo $readcsv[0][2]
But I am trying to use the value of the variable $row in stead of the first number while doing a while loop.
Something like:
echo $readcsv[$row][2]
I have tried next(), str_replace() and strtr() but none of them seems to work while the loop is running.
$row = 1;
$readcsv = array();
if (($handle = fopen("file.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$num = count($data);
echo $readcsv[$row][2];
$row++;
for ($c=0; $c < $num; $c++) {
}
$mycsvfile[] = $data;
}
fclose($handle);
}
CSV file:
title;image_link;link;empty;price;
1;back.gif;http://link.com;;19.95;
2;back.gif;http://link.com;;19.95;
3;back.gif;http://link.com;;19.95;
4;back.gif;http://link.com;;19.95;
5;back.gif;http://link.com;;19.95;
I am not quite sure from your code and question exactly what you are trying to do, but maybe its something like this
if (($handle = fopen("file.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
// you load the line into $data and its a one dimentional array
// occurance 2 is the `link` (http://link.com) if that what you want to echo
echo $data[2];
// as you have a loop, maybe you were trying to
// echo each fields from the csv so you can do that like this
foreach ($data as $idx => $value) {
echo "Column $idx = $value";
}
$mycsvfile[] = $data;
}
fclose($handle);
}

PHP Get values from CSV into an array

I have the following csv file:
9 carat gold,11.87
18 carat gold,23.73
Silver,0.49
Platinum,27.52
I would like to put this in a Multidimensional Array but i have no idea how to.
Thanks for any help.
Try this code
$csv = file_get_contents($file);
$data = explode(PHP_EOL, $csv);
$arr = array();
foreach ($data as $entry) {
$arr[] = str_getcsv($entry);
}
print_r($arr);
You can go through this link for more details about str_getcsv function
You can use fgetcsv to parse a CSV file without having to worry about parsing it yourself.
Example from PHP Manual:
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
You can use fgetcsv to read a csv file open with fopen.

Encapsulating and reading into an array from text file

I'm trying to make 2 classes, to encapsulate these text files, Customer.txt and Orders.txt. The customer one I need to read each line into a separate instance of an array for each line of text, how can I do this?
Also, do I have to do something about the comma's in the text files?
I know I need to use fopen, just not sure how to go about doing it.
This is what I've tried so far.
<?php
class readOrders{
$array_of_lines = fopen("orders.txt", 'r') or die("Failed to create file");
foreach($array_of_lines as $line) {
$pieces_of_line = explode(',', $line);
}
class readCustomers{
$array_of_more_lines = fopen("customers.txt", 'r') or die("Failed to create file");
foreach($array_of_more_lines as $line) {
$pieces_of_line = explode(',', $line);
}
?>
Here are my text files
Orders.txt
1,4,0133360903,Building Java Programs,Computer Science
2,6,0321836995,Mathematics All Around,Mathematics
3,24,0321825721,Mathematics for Elementary Teachers with Activity Manual,Mathematics
4,10,0133011208,Business Math,Business
customers.txt
2,Leonie,Köhler,leonekohler#surfeu.de,University of Stuttgart,Theodor-Heuss-Straße 34,Stuttgart,,Germany,70174,+49 0711 2842222
3,Bjørn,Hansen,bjorn.hansen#yahoo.no,University of Oslo,Ullevålsveien 14,Oslo,,Norway,0171,+47 22 44 22 22
4,François,Tremblay,ftremblay#gmail.com,McGill University,1498 rue Bélanger,Montréal,QC,Canada,H2G 1A7,+1 (514) 721-4711
I think fgetcsv will be useful here, example from php-doc:
<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>

how to extend the length of time when fgetcsv function of php is reading csv file?

am having a problem here, i read a csv file using fgetcsv function then loop it, and write it into an xml file...when am using the script in a not so big data, everything works perfectly and writes the xml file....but when i use it in a huge csv, the xml can't finished being written and end up in an unclosed token thing
if (($handle = fopen("C:\\xampp\htdocs\yii\branch\seo_tagsdev.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 10000000, ",")) !== FALSE) {
$num = count($data);
// echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++)
{
$url = $doc->createElement('url');
$root->appendChild($url);
$loc = $doc->createElement('loc',htmlentities($data[$c]));
$url->appendChild($loc);
$lastmod = $doc->createElement('lastmod',date('Y-m-d'));
$url->appendChild($lastmod);
$freq = $doc->createElement('changefreq','daily');
$url->appendChild($freq);
$priority = $doc->createElement('priority',0.9);
$url->appendChild($priority);
// echo $data[$c] . "<br />\n";
}
$doc->save("C:\\xampp\htdocs\yii\branch\seo_tagsdev.xml");
}
i even adjusted the length parameter of fgetcsv and yet it doesn't work at all

Categories