PHP read text file and display formatted results - php

My goal is to use PHP to read data from a text file and display a page based on said data.
The text file would look something like this...
joe smith|ceo|chief executive officer|10|14|126
Jane Doe|cfo|chief financial officer|8|12|94
What I need to be able to do is read the text file, extract each of the values, separated by the "|" token, and format the output in a table-like display. When reading the text file, the first column (name) equates to a picture, located in a subfolder. Therefore, the output should look something like this...
Can anyone out there assist with this request?
Thanks in advance.

You need something like that:
I would save the Data in this example in a file called test.csv
But I think you get some problems with the first row. A Space in the src of the img-Tag....
I would replace the space from the Name with str_replace() in the PHP
and the space in the name of the Pictures with Underscrore "_"
<?php
echo '<table>';
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "|")) !==false) {
$num = count($data);
//print_r($data);
echo "<tr> ";
$row++;
for ($c=0; $c <= $num; $c++) {
if ($c==0){
echo '<td><img src="YOUR/SUBFOLDER/"'.$data[$c]
."/>".$data[$c].'</td>';
}else{
echo '<td>'.$data[$c] .'</td>';
}
}
echo "</tr> \n";
}
fclose($handle);
echo '</table>';
}
?>
Hope It Helps :-).
Sorry for my bad english

Related

parse CSV file in PHP by column

I want to open CSV (comma separated value) file in PHP by column, i want to take all datas from 3 columns. I tried with this code, but this only shows me data by row:
$row = 1;
if (($handle = fopen("ut.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 i can take all datas from one column ?
EXAMPLE:
This i my file in Excel, which is exported to SCV:
http://prntscr.com/mzcfcw
I want to take in php values from colum Name and Price and find duplicate values in column Name, compare their prices.
fgetcsv parses the given handle line by line (rows). It isn't possible to parse a csv file by column using core php. However, if you know the position of the 3 columns for which you wish to access the values, you could simply ignore all other columns:
//position (zero indexed) of required columns
$columnsToProcess=[0,3,4]
for ($c=0; $c < $num; $c++) {
//do something with value if column's index is in the required columns array
if(in_array($c,$columnsToProcess)){
//value at position $c equals $data[$c]
echo $data[$c] . "<br />\n";
}
}
Moe info about fgetcsv : http://php.net/manual/en/function.fgetcsv.php

Trouble understanding a PHP code sample

I've been looking around to see if anyone else has dissected this code already, but that has proven to be futile. I'm having some trouble understanding what's happening in this php code sample from here.
I'm still currently very new to programming and PHP as a whole so I'm hoping someone can give me a clean explanation (I have read the documentation, but I still fail to fully understand the code)
I'm currently tackling on a project to convert an uploaded CSV file into an array and then into a database. The sample code is below:
Example #1 Read and print the entire contents of a 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);
}
?>
I guess my problem really is with understanding the fgetcsv method, but if someone could provide me with a breakdown it would really be appreciated.
$row = 1;
Sets the initial number of rows processed.
if (($handle = fopen("test.csv", "r")) !== FALSE) {
Attempts to open the file (for reading only), continuing only if it can.
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
Iterates over each line in the CSV (with a maximum length of the row being 1,000 characters and the field delimiter being a comma), continuing only if it can, pulling the row out as an indexed array of the fields.
$num = count($data);
Gets the number of fields in the row.
echo "<p> $num fields in line $row: <br /></p>\n";
Outputs the number of fields in the given row.
$row++;
Increments the row number.
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
Iterates over each field in the row and outputs its value.
fclose($handle);
Closes the file.
fgetcsv reads your csv row-by-row.
It return ana associative array. If you have 10 columns in the csv for example:
csv1,csv2,csv3,...csv10 the $data variable each cycle will be an array like (csv1 => "value"1 ... csv10->"value10")
So your code print first the num of columns of the csv file
count($data)
then iterate the row taken from csv and print all the columns values
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
This is done for each row of the file

php read CSV with various amount of delimiters

I've got a script that reads in from a CSV file and sometimes the CSV files it receives contains an uneven amount of delimiters/columns so the first row could have 30 columns, the 2nd could have 20, etc. I can think of a few solutions myself ie:
Count the delimiters in the widest row, then append the proper amount to each row that is short to make them even.
But I was wondering if anyone had a more elegant method of doing this.
It depends on what you are using to read the CSV the most elegant have seen is fgetcsv Please see http://www.php.net/manual/en/function.fgetcsv.php for more information
There is an example there that counts number of CSV:
$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);
}

Problem with .csv file and missed comma(s)

Hi all I have a problem with CSV opening through PHP code. My PHP code is:
<?php
header("Content-Type: text/html; charset=windows-1251");
echo "<html>
<head>
<title></title>
</head>
<body>
";
$file = "import.csv";
if(file_exists($file)) {
if (($fopen = fopen($file, "r")) !== FALSE) {
echo "<table>\n";
while (($data = fgetcsv($fopen, 1024, ",")) !== FALSE) {
$max = count($data);
$num++;
echo "<tr>\n<td>".$num."</td>\n";
for ($i=0;$i<$max;$i++) {
echo "<td>".$data[$i]."</td>\n";
}
echo "</tr>\n";
}
echo "</table>";
fclose($fopen);
}
}
else {
echo "File doesn't exists!";
}
echo "
</body>
</html>";
?>
The problem isn't in PHP code, the problem is in .csv file. PHP code must work even if there is missing comma, when it show the information the normal way.
The .csv file:
First name,Family,Sex,Date of birth,City,Phone number
One, Ofamily, Male, 1975, LA,13-25-16
Two, Tfamily, Male, 1955, LV, 555-14345
Three, Thfamily, Male, 1958, NY, 15689
Four, Ffamily, Female, 1974, SF, 5897912
Five, Fifamily, Male, 1991, LA, 123456789
Six, Sfamily, Male, 1967, 9876542
Seven, Sefamily, Female,, SF,
<?php
header("Content-Type: text/html; charset=windows-1251");
echo "<html>
<head>
<title></title>
</head>
<body>
";
$file = "import.csv";
if(file_exists($file)) {
if (($fopen = fopen($file, "r")) !== FALSE) {
echo "<table>\n";
while (($data = fgetcsv($fopen, 1024, ",")) !== FALSE) {
$num++;
echo "<tr>\n<td>".$num."</td>\n";
foreach($data as $k => $v) {
switch ($k) {
case 0 : // first name
case 1 : // family
case 2 : // sex
case 4 : // city
if (is_numeric($v)) {
array_splice($data,$k,0,'');
}
break;
case 3 : // date of birth
case 5 : // phone number
if (!is_numeric($v)) {
array_splice($data,$k,0,'');
}
break;
}
}
foreach($data as $v) {
echo "<td>".$v."</td>\n";
}
echo "</tr>\n";
}
echo "</table>";
fclose($fopen);
}
}
else {
echo "File doesn't exists!";
}
echo "
</body>
</html>";
?>
If you don't have control of the incoming CSV, you're not going to be able to use fgetcsv. How is it supposed to know if there's a missing ,?
Unfortunately, you're going to have to write your own function to handle this. I would start by reading each line into an array. Then looping through the line and explodeing them by a comma. Then, you'll have to check each value and try to determine if somethings missing from the resulting array.
Let's look at the problematic line in your example.
Six, Sfamily, Male, 1967, 9876542
Here's what we know about it:
It contains one less value then all the rest, so we should run some data consistency checks on it.
We know the first and second values are going to be strings that do not equal "Male" or "Female".
We know the third value should always equal either "Male" or "Female".
We know the fourth value is going to be a year and should always be a numerical value.
We know the fifth value is missing and it should be a city code and will always be two letters in length.
Based on that information, you should be able to write some checks to determine if one of those values doesn't equal what you'd expect, and then fix it.
The problem is most likely to do with lines like:
Six, Sfamily, Male, 1967, 9876542
Where there is no city information. In this case, you'll never get "9876542" to show up in the phone column unless you apply some logic to determine that this isn't the city, and to skip to the next column. What you should do though, so that you have 6 columns in each row, is that instead of resetting $max every time, you should just set it once after reading the header. Then display that number of columns from each row you read.

PHP Grab last 15 lines in txt file

Thank you for taking the time to read this and I will appreciate every single response no mater the quality of content. :)
Using PHP, I'm trying to get the last 15 lines of a text document (.txt) and store that data into a php variable. I understand that this is possible, however when I do get the last 15 lines, is it possible to retain the order? For example:
text document:
A
B
C
When I grab the text document from the last 15 characters, I don't want the echo to end up like:
C
B
A
All assistance is appreciated and I look forward to your replies; thank you. :) If I didn't explain anything clearly and/or you'd like me to explain in more detail, please reply. :)
Thank you.
Try using array_slice, which will return a part of an array. In this case you want it to return the last 15 lines of the array, so:
$filearray = file("filename");
$lastfifteenlines = array_slice($filearray,-15);
If you don't mind loading the entire file into memory:
$lines = array_slice(file('test.txt'), -15);
print_r($lines );
If the file is too large to fit into memory you can use a circular method:
// Read the last $num lines from stream $fp
function read_last_lines($fp, $num)
{
$idx = 0;
$lines = array();
while(($line = fgets($fp)))
{
$lines[$idx] = $line;
$idx = ($idx + 1) % $num;
}
$p1 = array_slice($lines, $idx);
$p2 = array_slice($lines, 0, $idx);
$ordered_lines = array_merge($p1, $p2);
return $ordered_lines;
}
// Open the file and read the last 15 lines
$fp = fopen('test.txt', 'r');
$lines = read_last_lines($fp, 15);
fclose($fp);
// Output array
print_r($lines);
This method will also work if the file has less than 15 lines- returning an array with however many lines are in the file.
You can use fseek with a negative position to seek backwards through the file, counting newlines as you go.
I'm too tired to write up copy/past-able code, but there are some examples in the comments to the manual page for fseek that are very close to what you want.
If the file isn't bigger than available memory you can do this:
$fArray = file("filename");
$len = sizeof($fArray);
for($i=$len -15;$i<$len ;$i++)
{
echo $fArray[$i];
}
If you have a file that is hundreds of megabytes :
$rc = fopen("file","r");
for ($i=0; $line = fgets($file) ;$i++)
{
if ($i%15 == 0)
{
$last15 = array();
}
$last15[] = $line;
}
echo join("\n",$last15);
the longer array solution:
array_slice(explode("\n",file_get_contents($file)),-15);
the shorter array solution:
array_slice(file($file),-15);
This code will open the file, show the total lines, show the header of file and show the last lines of file defined in $limit.
<?php
// open the file in read mode
$file = new SplFileObject('file.csv', 'r');
// get the total lines
$file->seek(PHP_INT_MAX);
$last_line = $file->key();
echo $last_line;
echo "<br>";
// Rewind to first line to get header
$file->rewind();
// Output first line if you need use the header to make something
echo $file->current();
echo "<br>";
// selecting the limit
$limit = 6;
// selecting the last lines using the $limit
$lines = new LimitIterator($file, $last_line - $limit, $last_line);
//print all the last 6 lines array
//print_r(iterator_to_array($lines));
//echo "<br>";
// Loop over whole file to use a single line
foreach ($lines as $line) {
print_r($line);
echo "<br>";
}

Categories