how to query a csv value in php? - php

I'm currently using this script:
<?php function jj_readcsv($filename, $header=false) { $handle = fopen($filename, "r"); echo '<table>'; //display header row if true if ($header) {
$csvcontents = fgetcsv($handle);
echo '<tr>';
foreach ($csvcontents as $headercolumn) {
echo "<th>$headercolumn</th>";
}
echo '</tr>'; } // displaying contents while ($csvcontents = fgetcsv($handle)) {
echo '<tr>';
foreach ($csvcontents as $column) {
echo "<td>$column</td>";
}
echo '</tr>'; } echo '</table>'; fclose($handle); } jj_readcsv('partitiontable.csv',true);
?>
I have a CSV table with 8 columns.
I would like to know if it possible to get only on element of the column when making a query. Here is what look like my CSV :
"HEMSI, Alberto",P_000001,P_1,Partition,169864,"Hemsi, Myriam","HEMSI, Alberto","Una matica de ruda",
"HEMSI, Alberto",P_000002,P_2,Partition,169865,"Hemsi, Myriam","HEMSI, Alberto","Ya salio de la mar",
the idea is :
query a value for example: P_1
and get in result: Una matica de ruda
For each line, when asking P_1 getting the value which is in the 8 column.
And the same for P_2

Yes, this is possible using two methods:
At the beginning create an associative array and insert as key the 4th column, and as value with 8th column. Then use this as a lookup table in all further code.
If you don't do 1. , you can make a for loop that goes through the CSV data and looks with IF that the 4th row value is the one you are looking for. When found, return the 8th column value.
Example of first approach with associative array
<?php
$array = array();
jj_readcsv("csv.txt");
echo $array["P_1"]."<br/>";
echo $array["P_2"]."<br/>";
function jj_readcsv($filename, $header = false)
{
global $array;
$row = 1;
if (($handle = fopen($filename, "r")) !== FALSE) {
echo '<table>'; //display header row if true if ($header) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
//print_r($data);
$num = count($data);
echo '<tr>';
for ($c=0; $c < $num; $c++) {
if($row > 1)
echo "<td>$data[$c]</td>";
else
echo "<th>$data[$c]</th>";
if($c==2)
$array[$data[$c]]= $data[7];
}
echo '</tr>';
$row++;
}
fclose($handle);
}
}
?>

Try this:
$row = 1;
$handle = fopen ("teste.csv","r");
$head = Array();
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
//register head rows with names
if($row == 1){
$num = count ($data);
for ($c=0; $c < $num; $c++) {
$colName = trim($data[$c]);
$head[$colName] = $c;
}
}else{
echo $data[$head['COL_NAME']];
}
$row++;
}
fclose ($handle);
This will make var $head an associative array where the key is the col name and value his position in csv, after that you can easy identify what col you want.

Even if you named your function jj_readcsv(), if you look more closely, this name is a liar, the function does much more: opening a file, reading the lines.
If you don't want to separate the concerns but also easily modify it, just make the actual reading method optional:
function jj_readcsv($filename, $header = FALSE, callable $fgetcsv = NULL)
########################
{
$fgetcsv || $fgetcsv = 'fgetcsv';
#################################
$fileHandle = fopen($filename, "r");
if (!$fileHandle) {
return;
}
$csvLine = $fgetcsv($fileHandle);
#####################
echo '<table>';
echo '<tr>';
foreach ($csvLine as $headercolumn) {
echo "<th>$headercolumn</th>";
}
echo '</tr>';
while ($csvLine = $fgetcsv($fileHandle)) {
#####################
echo '<tr>';
foreach ($csvLine as $column) {
echo "<td>$column</td>";
}
echo '</tr>';
}
echo '</table>';
fclose($fileHandle);
}
This little modification allows you to specify the reading function, therefore you can control what is read. So you can inject it as third parameter, for example to only return the eighth column:
jj_readcsv('test.csv', FALSE, function($fileHandle) {
if ($csvLine = fgetcsv($fileHandle))
{
$csvLine = [$csvLine[7]];
}
return $csvLine;
});
Output:
<table><tr><th>Una matica de ruda</th></tr><tr><td>Ya salio de la mar</td></tr></table>

Related

how do I check at which line the value changes in a csv file?

I'm creating a table with telephone number of the a company those are separated in different organizations and in other departments. I have those informations saved in a CSV file.
My Question is how can i check when the department changes so that i can make a Spacing or that i can style it later on?
This is the Structure of my CSV file.
organization;name;phonenumber;department
PHP script:
function printPhonenumbers($org) {
$handle = fopen ('csvPHP.csv','r');
while (($csv_array = fgetcsv ($handle, 0, ';')) !== FALSE ) {
for ($i=5; $i <= count($csv_array) ; $i=$i+1) {
if ($csv_array[0] == $org) {
echo "<tr>";
echo "<td>".$csv_array[1]."</td>";
echo "<td>".$csv_array[2]."</td>";
echo "</tr>";
}
}
}
fclose($handle);
}
As #matiit pointed out, try and remember the last known value:
Example:
function printPhonenumbers($org) {
$handle = fopen ('csvPHP.csv','r');
$last_department = null;
while (($csv_array = fgetcsv ($handle, 0, ';')) !== FALSE ) {
for ($i=5; $i <= count($csv_array) ; $i=$i+1) {
if ($last_department != $csv_array[3]) {
// here the department is different from the previous one. Remember to 'save' the new value
$last_department = $csv_array[3];
// do your thing
} else {
// still the same department
if ($csv_array[0] == $org) {
echo "<tr>";
echo "<td>".$csv_array[1]."</td>";
echo "<td>".$csv_array[2]."</td>";
echo "</tr>";
}
}
}
}
fclose($handle);
}

How to output random data from CSV in php?

I have a CSV file with 100 rows but want to output 5 of them at random like $data[0][1][2][3] and $data[2][2][3]
I got it to show but it shows in a group
<?php
$row = 1;
if (($handle = fopen("Book1.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
Would like it to look like:
some data:<?php echo $data[0][1][2][3];?>
more data:<?php echo $data[1][1][2][3];?>
more data:<?php echo $data[5][1][2][3];?>
more data:<?php echo $data[8][1][2][3];?>
If you load the file into an array, it's easy enough to come up with a list of "random" numbers, pull the corresponding line out, and use str_getcsv the same way you used fgetcsv in your code. It isn't the most efficient way to do it, as you need to read the whole file into memory. But it's necessary to determine the number of lines before choosing your random number.
<?php
$rows = file("Book1.csv");
$len = count($rows);
$rand = [];
while (count($rand) < 5) {
$r = rand(0, $len);
if (!in_array($r, $rand)) {
$rand[] = $r;
}
}
foreach ($rand as $r) {
$csv = $rows[$r];
$data = str_getcsv($csv);
// now do whatever you want with $data, which is one random row of your CSV
echo "first column from row $r: $data[0]\n";
}

Pass php drop down value to another php site

I am new to php, and would like to pass a drop down menu value to another php file. Below is the code I have pieced together so far.
Drop down php (Lists all files in a directory, although i'd like to omit the folders and the "." & ".."):
<?php
$currentdir = 'data/';
$dir = opendir($currentdir);
echo 'Files are as follows:<br>';
echo '<form action="SelectedDate.php" method="POST">';
echo '<select name="selectedfile" onchange="this.form.submit()">';
while($file = readdir($dir))
{
echo '<option value="'.$file.'">'.$file.'</option>';
}
echo '</select>';
echo '</form>';
closedir($dir);
?>
Table generating php, which is where i'd like to pass the file name too so it can pull up the selected csv file,formatted to table. :
<?php
$var=$_REQUEST['selectedfile'];
$row = 1;
if (($handle = fopen('"data/"'$var'"', "r")) !== FALSE) {
echo '<head>';
echo '<script src="js/sorttable.js"></script>';
echo '</head>';
echo '<table class="sortable" border="1">';
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
if ($row == 1) {
echo '<thead><tr>';
}else{
echo '<tr>';
}
for ($c=0; $c < $num; $c++) {
//echo $data[$c] . "<br />\n";
if(empty($data[$c])) {
$value = " ";
}else{
$value = $data[$c];
}
if ($row == 1) {
echo '<th>'.$value.'</th>';
}else{
echo '<td>'.$value.'</td>';
}
}
if ($row == 1) {
echo '</tr></thead><tbody>';
}else{
echo '</tr>';
}
$row++;
}
echo '</tbody></table>';
fclose($handle);
}
?>
I cant seem to get the drop down value to pass into the fopen() function...
Any help and critiquing would be great!
For readability I would prefer $_POST instead of $_REQUEST, besides that you have an error:
(($handle = fopen('"data/"'$var'"', "r"))
//SHOULD BE:
(($handle = fopen("data/".$var.", "r"))
======
Updated answer:
Make sure your files are both saved with an .php extension. Besides that, add the following lines of code to the top of your second file:
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
As a finishing try, use this code in the if
(($handle = fopen("data/{$var}", "r"))
Change this line:
if (($handle = fopen('"data/"'$var'"', "r")) !== FALSE) {
Into
if (($handle = fopen('"data/"'.$var.'"', "r")) !== FALSE) {
Note the dots!

Create HTML table from multiple lines of strings

I want to take a text file formatted like so:
*note I can change the format of the stored messages, basically there are delimiters and different lines
;68.229.164.10:4/5/2013:Hello
;71.73.174.13:4/6/2013:Oh Hey
(;IPADDRESS:TIMESTAMP:MESSAGE)
and put it in a table that looks like so:
IP Time Message
68.229.164.10 4/6/2013 Hello
71.73.174.13 4/6/2013 Oh Hey
I prefer to use something like the following:
http://php.net/manual/en/function.fgetcsv.php
And then format the output accordingly.
From Example 1 on the above referenced page:
<?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);
}
?>
so, you could do something like this...
<?php
$row = 1;
if (($handle = fopen("path_to_your_data_file", "r")) !== FALSE) {
echo '<table>';
echo '<tr><td></td>IP<td>Time</td><td>Message</td></tr>';
while (($data = fgetcsv($handle, 1000, ":")) !== FALSE) {
$num = count($data);
$row++;
if ($num > 2) {
echo '<tr>';
for ($c=0; $c < $num; $c++) {
echo '<td>'.$data[$c].'</td>';
}
echo '</tr>';
}
}
echo '</table>';
fclose($handle);
}
?>
$a=";68.229.164.10:4/5/2013:Hello
;71.73.174.13:4/6/2013:Oh Hey";
preg_match_all('{;(.*?):(.*?):(.*)}',$a,$d);
//set th
$d[0][0]='IP';
$d[0][1]='TIME';
$d[0][2]='Message';
$table = '<table>'.PHP_EOL;
foreach($d AS $tr){
$row = PHP_EOL;
foreach($tr AS $td){
$row .= "<td>{$td}</td>".PHP_EOL;
}
$table .= "<tr>{$row}</tr>".PHP_EOL;
}
$table .= "</table>".PHP_EOL;
echo $table;

CSV to Json with header row as key

I would like to convert a CSV to Json, use the header row as a key, and each line as object. How do I go about doing this?
----------------------------------CSV---------------------------------
InvKey,DocNum,CardCode
11704,1611704,BENV1072
11703,1611703,BENV1073
---------------------------------PHP-----------------------------------
if (($handle = fopen('upload/BEN-new.csv'. '', "r")) !== FALSE) {
while (($row_array = fgetcsv($handle, 1024, ","))) {
while ($val != '') {
foreach ($row_array as $key => $val) {
$row_array[] = $val;
}
}
$complete[] = $row_array;
}
fclose($handle);
}
echo json_encode($complete);
Just read the first line separately and merge it into every row:
if (($handle = fopen('upload/BEN-new.csv', 'r')) === false) {
die('Error opening file');
}
$headers = fgetcsv($handle, 1024, ',');
$complete = array();
while ($row = fgetcsv($handle, 1024, ',')) {
$complete[] = array_combine($headers, $row);
}
fclose($handle);
echo json_encode($complete);
I find myself converting csv strings to arrays or objects every few months.
I created a class because I'm lazy and dont like copy/pasting code.
This class will convert a csv string to custom class objects:
Convert csv string to arrays or objects in PHP
$feed="https://gist.githubusercontent.com/devfaysal/9143ca22afcbf252d521f5bf2bdc6194/raw/ec46f6c2017325345e7df2483d8829231049bce8/data.csv";
//Read the csv and return as array
$data = array_map('str_getcsv', file($feed));
//Get the first raw as the key
$keys = array_shift($data);
//Add label to each value
$newArray = array_map(function($values) use ($keys){
return array_combine($keys, $values);
}, $data);
// Print it out as JSON
header('Content-Type: application/json');
echo json_encode($newArray);
Main gist:
https://gist.github.com/devfaysal/9143ca22afcbf252d521f5bf2bdc6194
For those who'd like things spelled out a little more + some room to further parse any row / column without additional loops:
function csv_to_json_byheader($filename){
$json = array();
if (($handle = fopen($filename, "r")) !== FALSE) {
$rownum = 0;
$header = array();
while (($row = fgetcsv($handle, 1024, ",")) !== FALSE) {
if ($rownum === 0) {
for($i=0; $i < count($row); $i++){
// maybe you want to strip special characters or merge duplicate columns here?
$header[$i] = trim($row[$i]);
}
} else {
if (count($row) === count($header)) {
$rowJson = array();
foreach($header as $i=>$head) {
// maybe handle special row/cell parsing here, per column header
$rowJson[$head] = $row[$i];
}
array_push($json, $rowJson);
}
}
$rownum++;
}
fclose($handle);
}
return $json;
}

Categories