PHP Get values from CSV into an array - php

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.

Related

Open csv file improper encoding

When I open the csv file
$str = file_get_contents($filename);
$str = mb_convert_encoding($str,"utf-8","sjis");
var_dump($str);
It shows like this
\0000\000.\0000\0000\0008\0000\0005\0007\000,\0000\000.\0000\0001\0000 ....
At first I think , this is the problem of encoding, so I added mb_convert_encoding but in vain.
What cause this improper encoding?
Better you can do like this:
$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);
}
Code copied from :http://php.net/manual/en/function.fgetcsv.php
alternatively : http://php.net/manual/en/function.str-getcsv.php

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);
}
?>

CSV not properly being parsed on new lines

I have a CSV file that looks like:
Header1,Header2,Header3
value1,value2,value3
value11,value12,value13
value21,value22,value23
etc...
When I use this code to parse through it:
$csvData = file_get_contents($file_url);
$lines = explode(" ", $csvData);
$array = array();
foreach ($lines as $line) {
$array[] = str_getcsv($line);
}
dpm($array);
the first value of a line always ends up being part of the end of the last header:
EDIT: There must have been an issue with cache as this is working fine.
For reading CSV file explode() and file_get_contents() are not the correct options. Go for fgetcsv
You can do like below for reading CSV file:
<?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);
}
?>
Use file instead of file_get_contents. That will return an array with one line of the input file on each index. This will work with all possible new line characters.
$lines = file($file_url, FILE_IGNORE_NEW_LINES)
You might want to break lines into newlines ("\n") instead of just spaces (" "). Even better, you might want to use file() to load file lines into an array. Better yet, you might want to use SplFileObject class to do that:
<?php
$file = new SplFileObject($file_url);
$file->setFlags(SplFileObject::READ_CSV | SplFileObject::SKIP_EMPTY
| SplFileObject::DROP_NEW_LINE | SplFileObject::READ_AHEAD);
$data = array();
foreach ($file as $row) {
$data[] = $row;
}
Good luck!

Reading CSV in PHP and out put its contents by array value

I want to display the contents of a CSV file by assigning it to a variable and then display it using echo statement.
This code is not working could someone point the error in it
$fh = fopen('db.csv', 'r');
$now = time();
$data=fgetcsv($fh);
$data[0]=$name;
echo $name;
Am a newbie to coding and scripting.
Thanks
This is the CSV line that I want to be printed
katz,26-11-2011,http//www.google.com
Why you first valorize the $data with an array of your CSV and then you overwrite the first position with the $name variable (which apparently is null)?
$data[0] = $name;
should be
$name = $data[0];
You could use the handy fgetcvs function for this.
Might as well post an example for want of a complete answer, shamelessly ripped from that same
manpage:
<?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);
}
?>
Hope that fits your needs. Happy coding.

reading first 5 fields of csv file in php

I am confused on how to read a csv file in php ( only the first 4 fields) and exclude the remaining fileds.
Sno,Name,Ph,Add,PO
1,Bob,0102,Suit22,89
2,Pop,2343,Room2,78
I just want to read first 3 fileds and jump to next data. cannot figure out how to do through fgetcsv
any help?
Thanks,
I added a comment to the sample fgetcsv code for you:
$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";
// iterate over each column here
for ($c=0; $c < $num; $c++) {
// handle column data here
echo $data[$c] . "<br />\n";
// exit the loop after 3rd column parsed
if ($c == 2) break;
}
++$row;
}
fclose($handle);
}
Here's a way to do it without the fgetcsv function:
$lines = file('data.csv');
$linecount = count($lines);
for ($i = 1; $i < $linecount; $i++){
$fields = explode(',', $lines[$i]);
$sno = $fields[0];
$name = $fields[1];
$ph = $fields[2];
$add = $fields[3];
}

Categories