select some csv values to export in html table with php - php

I've copied this php:
<?Php
echo "<html><body><table border=1>";
$f = fopen("datos.csv", "r");
$fr = fread($f, filesize("datos.csv"));
fclose($f);
$lines = array();
$lines = explode("\r\n",$fr); // IMPORTANT the delimiter here just the "new line" \r\n, use what u need instead of...
for($i=0;$i<count($lines);$i++) {
echo "<tr>";
$cells = array();
$cells = explode(",",$lines[$i]); // use the cell/row delimiter what u need!
for($k=0;$k<count($cells);$k++) {
echo "<td>".$cells[$k]."</td>";
}
// for k end
echo "</tr>";
}
// for i end
echo "</table></body></html>";
?>
This code generates the html table. I have a csv with one column with diferent values separated with comma, and I want only some values.
The question is the loop with the variable $k to catch only value2, value4, value7 ,...
I appreciate some help, I'm learning php but I start in advanced mode :-(
and I search this site but don't find it.

Its always dangerous to read a whole file into memory, eventually you will find a file that is large enough to blow the script up because it is Too Large to read into memory.
Use fgetcsv() instead in this situation. This reads one line at a time from your csv file, into an array, all you then have to do is pick the occurances (columns) you actually want to process.
if (($handle = fopen("datos.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 2000, ",")) !== FALSE) {
// pick the columns you are interested in
// remember arrays start at index 0
echo sprintf('The bits I am interested in %s, %s, %s<br>',
$data[2], $data[4], $data[7]);
}
fclose($handle);
}

Related

to change csv file format and read one row with key value of csv

I have got a csv file, this csv file does not has a comma(,) among values but it has a cap (^) symbol.
I need to do two things now.
1. To change this cap and get comma after each value from csv.
2. I need to read one whole csv file that has almost 37 columns into once row of array along with first column as the key of array.
These both things have to be done using php.
I am trying through online exmaples like
function csv_to_array($filename='mycsv.csv', $delimiter=',')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen('mycsv.csv', 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
The thing I am confused is my actual csv file is "abc"^"def"^" so abc is one value and def is another and both are separated by ^ how can I say first remove ^ take whole string start from " and end at " and add a comma.
I want something like this with array

Finding duplicate column values in a CSV

I'm importing a CSV that has 3 columns, one of these columns could have duplicate records.
I have 2 things to check:
1. The field 'NAME' is not null and is a string
2. The field 'ID' is unique
So far, I'm parsing the CSV file, once and checking that 1. (NAME is valid), which if it fails, it simply breaks out of the while loop and stops.
I guess the question is, how I'd check that ID is unique?
I have fields like the following:
NAME, ID,
Bob, 1,
Tom, 2,
James, 1,
Terry, 3,
Joe, 4,
This would output something like `Duplicate ID on line 3'
Thanks
P.S this CSV file has more columns and can have around 100,000 records. I have simplified it for a specific reason to solve the duplicate column/field
Thanks
<?php
$cnt = 0;
$arr=array();
if (($handle = fopen("1.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num=count($data);
$cnt++;
for ($c=0; $c < $num; $c++) {
if(is_numeric($data[$c])){
if (array_key_exists($data[$c], $arr))
$arrdup[] = "duplicate value at ".($cnt-1);
else
$arr[$data[$c]] = $data[$c-1];
}
}
}
fclose($handle);
}
print_r($arrdup);
Give it a try:
$row = 1;
$totalIDs = array();
if (($handle = fopen('/tmp/test1.csv', "r")) !== FALSE)
{
while (($data = fgetcsv($handle)) !== FALSE)
{
$name = '';
if (isset($data[0]) && $data[0] != '')
{
$name = $data[0];
if (is_numeric($data[0]) || !is_string($data[0]))
echo "Name is not a string for row $row\n";
}
else
{
echo "Name not set for row $row\n";
}
$id = '';
if (isset($data[1]))
{
$id = $data[1];
}
else
{
echo "ID not set for row $row\n";
}
if (isset($totalIDs[$id])) {
echo "Duplicate ID on line $row\n";
}
else {
$totalIDs[$id] = 1;
}
$row++;
}
fclose($handle);
}
I went assuming a certain type of design, as stripped out the CSV part, but the idea will remain the same :
<?php
/* Let's make an array of 100,000 rows (Be careful, you might run into memory issues with this, issues you won't have with a CSV read line by line)*/
$arr = [];
for ($i = 0; $i < 100000; $i++)
$arr[] = [rand(0, 1000000), 'Hey'];
/* Now let's have fun */
$ids = [];
foreach ($arr as $line => $couple) {
if ($ids[$couple[0]])
echo "Id " . $couple[0] . " on line " . $line . " already used<br />";
else
$ids[$couple[0]] = true;
}
?>
100, 000 rows aren't that much, this will be enough. (It ran in 3 seconds at my place.)
EDIT: As pointed out, in_array is less efficient than key lookup. I've updated my code consequently.
Are the IDs sorted with possible duplicates in between or are they randomly distributed?
If they are sorted and there are no holes in the list (1,2,3,4 is OK; 1,3,4,7 is NOT OK) then just store the last ID you read and compare it with the current ID. If current is equal or less than last then it's a duplicate.
If the IDs are in random order then you'll have to store them in an array. You have multiple options here. If you have plenty of memory just store the ID as a key in a plain PHP array and check it:
$ids = array();
// ... read and parse CSV
if (isset($ids[$newId])) {
// you have a duplicate
} else {
$ids[$newId] = true; // new value, not a duplicate
}
PHP arrays are hash tables and have a very fast key lookup. Storing IDs as values and searching with in_array() will hurt performance a lot as the array grows.
If you have to save memory and you know the number of lines you going to read from the CSV you could use SplFixedArray instead of a plain PHP array. The duplicate check would be the same as above.

How can I parse a CSV with php but ignore the commas and double quotes in the strings

I am trying to parse a csv file into an array. Unfortunately one of the columns contains commas and quotes (Example below). Any suggestions how I can avoid breaking up the column in to multiple columns?
I have tried changing the deliminator in the fgetcsv function but that didn't work so I tried using str_replace to escape all the commas but that broke the script.
Example of CSV format
title,->link,->description,->id
Achillea,->http://www.example.com,->another,short example "Of the product",->346346
Seeds,->http://www.example.com,->"please see description for more info, thanks",->34643
Ageratum,->http://www.example.com,->this is, a brief description, of the product.,->213421
// Open the CSV
if (($handle = fopen($fileUrl, "r")) !==FALSE) {
// Set the parent array key to 0
$key = 0;
// While there is data available loop through unlimited times (0) using separator (,)
while (($data = fgetcsv($handle, 0, ",")) !==FALSE) {
// Count the total keys in each row
$c = count($data);
//Populate the array
for ($x = 0; $x < $c; $x++) {
$arrCSV[$key][$x] = $data[$x];
}
$key++;
} // end while
// Close the CSV file
fclose($handle);
}
Maybe you should think about using PHP's file()-function which reads you CSV-file into an array.
Depending on your delimiter you could use explode() then to split the lines into cells.
here an example:
$csv_file("test_file.csv");
foreach($csv_file as $line){
$cell = explode(",->", $line); // ==> if ",->" is your csv-delimiter!
$title[] = $cell[0];
$link[] = $cell[1];
$description = $cell[2];
$id[] = $cell[3];
}

Passing from a row informations to two array in php

I am beginner in php . In my application i have to read a csv file and store the values of each row in two variables: $name and latin.
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
foreach($data as $value)
{
if($i>8){
// $fgmembersite->InsertUserBirds($value);
echo $value;
}
}
$i++;
echo '<br/>' ;
} fclose($handle);
each row row contains four or three words ( $name is the first and the second word (if the length of row is 4 words) and the $latin store the last two words:
How can i do it to add the array $latin and $name ?
Seems this one is going to do exactly what you need:
$name = $latin = array();
while (($data = fgetcsv($handle, 1000, ",")) !== false) {
if (count($data) === 4) {
$name[] = $data[0];
$name[] = $data[1];
$latin[] = $data[2];
$latin[] = $data[3];
} elseif ($count($data) === 3) {
$name[] = $data[0];
$latin[] = $data[1];
$latin[] = $data[2];
}
}
The best way to handle this data is to look for a more reliable source!
If you have to use this file, try the following:
Use fgets to handle the file line by line.
All species names are lower cased and all Genus names are capitalised so you could search for the rightmost capital letter. Everything from that point on is Latin, everything to the left is Common.
A more elegant approach is to use preg_match to find the last capital letter. I'm not good at regexp so hopefully an improvement can be made on mine, but the below will return your latin name as the last index of the array 'matches'. If you have got this far, you should be able to figure the rest out.
$matches=array();
$pattern="/([A-Z][a-z ]*)*/";
$testdata="Scabies Mite Sarcoptes scabii";
preg_match($pattern,$testdata,$matches);
var_dump($matches);
Although it can seem daunting learning regexp at the same time as PHP, even a little effort will be well rewarded and there are many helpful members on this site.

How to create a sentence from CSV columns

My aim is to create a sentence consisting of three random words which are to be taken from the columns of a CSV file.
I am having troubles with making PHP choose the words only from the correct columns, hence column one contains the words to be first in the sentence, column two only middle words and column three only last words.
Example of the CSV file:
my;horse;runs
your;chicken;sits
our;dog;barks
Example of the output:
My chicken barks. *reload*
Your horse sits. *reload*
Our dog runs.
My effort so far:
<?php
$file = fopen('input.csv', 'r');
while (($line = fgetcsv($file, 1000, ";")) !== FALSE) {
$x = array_rand($line);
echo $line[$x] . "\n";
}
?>
Thanks in advance and forgive the strong noobness with this one, please.
This gives randomized sentences as requested:
<?php
$file = fopen('input.csv', 'r');
// prepare token contained
$line = array();
// read csv file line by line
while (!feof($file))
// fill single line into token container
$line[] = fgetcsv($file, 1000, ";");
// construct a sentence by picking random words from columns
$sentence = sprintf("%s %s %s\n",
$line[rand(0,sizeof($line)-1)][0],
$line[rand(0,sizeof($line)-1)][1],
$line[rand(0,sizeof($line)-1)][2] );
// output sentence
echo $sentence;
?>
However it is not very efficient, since it reads the whole csv file into memory first. So it only performs on smaller csv files (say up to a few hundred lines). For bigger files you should consider picking the random line number first and reading only that line from the file. Doing this three times gives you three words you can constrcut your sentence from.
I would sort the columns into separate arrays then select a random index.
<?php
$file = fopen('input.csv', 'r');
while (($line = fgetcsv($file, 1000, ";")) !== FALSE) {
$column1[] = $line[0];
$column2[] = $line[1];
$column3[] = $line[2];
}
function pickWord($wordArray){
$x = array_rand($wordArray);
echo $wordArray[$x] . "\n";
}
pickWord($column1);
pickWord($column2);
pickWord($column3);
?>
Something like that
Code
<?php
$csv = "my;horse;runs
your;chicken;sits
our;dog;barks";
$lines = explode( "\n", $csv );
foreach( $lines as $line ) {
echo ucfirst( str_replace( ";", " ", trim( $line ) ) ) . "<br />";
}
?>
Output
My horse runs
Your chicken sits
Our dog barks

Categories