Echo the bottom line of a CSV - php

I am attempting to echo the bottom line only of a .csv file. I echo the file in reverse order (as shown below) but I'm not sure how to only echo the top line of this. Please note that the csv variable, constantly changing.
Here is my php:
<?php
$file = file("file.csv");
$file = array_reverse($file);
foreach($file as $f){
echo $f."<br />";
}
?>

Simple solution is.
$file = "file.csv";
$data = file($file);
$last_line = $data[count($data)-1];

Maybe try the end function see http://php.net/manual/en/function.end.php
<?php
$file = file("file.csv"); // You take care of reading all the lines.
$lastline = end($file);
?>

<?php
$file = file("file.csv");
$last_line=count($file)-1;
echo $file[$last_line];
?>

Related

PHP Replace all values in the third column in a csv file

I am trying to replace some hyperlinks in a csv file, like this one:
[https://assets.suredone.com/683987/media-pics/6164307j-gabriel-61643-proguard-steel-shock-absorber-for-select-chevrolet-gmc-models.jpg. Here is my code:][1]. Here is my code:
<?php
$in_file = 'gabriel-images-urls.csv';
$out_file = 'results.csv';
$fd = fopen($in_file, "r");
$new_array= array();
$toBoot= array();
while ($data = fgetcsv($fd)) {
echo '<pre>';
if (strpos($data[2],'media-pics') !== false) {
$data[2]=str_replace('media-pics','media-photos',$data[2]);
fputcsv($fd, $data);
// echo $output;
}
}
?>
The new link for example must look like this:[1]https://assets.suredone.com/683987/media-photos/6164307j-gabriel-61643-proguard-steel-shock-absorber-for-select-chevrolet-gmc-models.jpg. The goal is he "media-pics" substring to be replaced with "media-photos". At this point nothing happens in the file. I think this is because the file is open only for reading but I am not sure.
Can you not simply do a string replacement on the whole file rather than attempting to load and process each line of the file using fgetcsv?
<?php
$srcfile='gabriel-images-urls.csv';
$outfile='results.csv';
$csvdata=file_get_contents( $srcfile );
$moddata=str_replace('media-pics','media-photos',$csvdata);
file_put_contents( $outfile, $moddata );
?>

Read serialized file, record by record

I save to file data from form:
$name = $_POST['name'];
$url = $_POST['url'];
$comm = $_POST['comm'];
$data["name"]=$name;
$data["url"]=$url;
$data["comm"]=$comm;
file_put_contents("db.txt", serialize($data));
Now, I would like to read this file record by record.
$file_handle = fopen("db.txt", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
$arr = unserialize($line);
var_dump($arr);
}
fclose($file_handle);
But this code read only last record. How to read all file?
Replace file_put_contents("db.txt", serialize($data)); to
file_put_contents("db.txt", PHP_EOL .serialize($data), FILE_APPEND);
file_put_contents("db.txt", serialize($data));// will over write the file again and again. so you cant able to read all the data. FILE_APPEND helps to append the data And PHP_EOL helps to leave a line breake.
Hi i try this code for your solution:
<?php
$name = "rdn";
$url = "http://google.it";
$comm = "com";
$data["name"]=$name;
$data["url"]=$url;
$data["comm"]=$comm;
file_put_contents("db.txt", serialize($data)."\n",FILE_APPEND);
$fh = fopen('db.txt','r');
while ($line = fgets($fh)) {
// <... Do your work with the line ...>
var_dump(unserialize($line));
}
fclose($fh);
?>
without "\n" don't work!

Get only one line from a web page

Hi, I have this file test1.php and in the other file test.php I have this
php code running:
<?php
$file = "http://inviatapenet.gethost.ro/sop/test1.php";
$line = '0';
if($f = fopen($file, 'r')){
$line = fgets($f); // read until first newline
fclose($f);
}
echo $line;
?>
The idea is to get just the second line of the web page test1.php.
Second Line
I've tried to change the $line = '2'; but no affect, it just displays the first line.
I need Help.
You can use file which reads a file into an array, you can then grab whichever line you want by using the index you want.
For example:
data.txt:
line one
line two
line three
line four
PHP code:
$file = file('data.txt');
echo $file[1]; // echo line number 2, remember arrays start at 0!
Updated PHP code for new versions (5.4):
echo file('data.txt')[1];
This should work. Obviously, change only the value of $linetofetch:
<?php
// Write here the number of the line you want to fetch.
$linetofetch = 2;
$file = "http://inviatapenet.gethost.ro/sop/test1.php";
$currentline = 1;
if($f = fopen($file, 'r')){
while ($currentline <= $linetofetch) {
$line = fgets($f); // read until first newline
$currentline++;
}
fclose($f);
}
echo $line;
?>

fGetCsv only reading first line?

I'm trying to use fgetCsv but for some reason it is only reading the first line. Here is the code:
$fieldseparator = ",";
$lineseparator = "\r";
if(!file_exists($csvFile)) {
echo "<div id='error'>Cannot find uploaded file. Please try again</div>";
exit;
}
$file = fopen($csvFile,"r");
if(!$file) {
echo "<div id='error'>Error loading CSV file</div>";
exit;
}
$size = filesize($csvFile);
if(!$size) {
echo "<div id='warning'>File is empty</div>";
exit;
}
$query = "";
$content = fgetcsv($file,$size,$lineseparator);
fclose($file);
foreach($content as $data) {
$values = explode($fieldseparator,$data);
$query[$i] = "('".implode("','",$values)."')";
}
This just outputs one line. Here is the CSV file:
TSE-P01,1,WO47653897,RM,EcoQuiet,1
TSE-P02,1,WO47653898,RM,EcoQuiet,1
TSE-P03,1,WO47653899,RM,EcoQuiet,1
TSE-P04,1,WO47653900,RM,EcoQuiet,1
TSE-P05,1,WO47653901,RM,EcoQuiet,1
TSE-P06,1,WO47653902,RM,EcoQuiet,1
TSE-P07,1,WO47653903,RM,EcoQuiet,1
TSE-P08,1,WO47653904,RM,EcoQuiet,1
Any ideas why this might be happening?
From the docs:
fgetcsv — Gets line from file pointer and parse for CSV fields
If you want more than one line then you need to call it more than once.
This example is the "Example 2" from w3schools http://www.w3schools.com/php/func_filesystem_fgetcsv.asp
$file = fopen("contacts.csv","r");
while(!feof($file))
{
print_r(fgetcsv($file));
}
fclose($file);
Using the while loop the code iterates through the whole file/all the lines..
Alternatively.. if you do something like that..
print_r(fgetcsv($file));
print_r(fgetcsv($file));
print_r(fgetcsv($file));
It will print only the first 3 lines..

How to correctly use the PHP function 'fgets'?

I assume I'm using the fgets() wrong. I'm tring to open a PHP file and then try to match a line in that file with a variable I create. If the line does match then I want to write/insert PHP code to the file right below that line. Example:
function remove_admin(){
$findThis = '<tbody id="users" class="list:user user-list">';
$handle = #fopen("../../fns-control/users.php", "r"); // Open file form read.
if ($handle) {
while (!feof($handle)) // Loop til end of file.
{
$buffer = fgets($handle, 479); // Read a line.
if ($buffer == '<tbody id="users" class="list:user user-list">') // Check for string.
{
Now I want to write PHP code to the file, starting on line 480. How can I do that?
Useful information may be: IIS 6 and PHP 5.2.
Try this:
<?php
function remove_admin(){
$path = "../../fns-control/users.php";
$findThis = '<tbody id="users" class="list:user user-list">';
$phpCode = '<?php echo \'hello world\'; ?>';
#Import file to string
$f = file_get_contents($path);
#Add in the PHP code
$newfile = str_replace($findThis, $findThis . $phpCode, $f);
#Overwrite the existing file
$x = fopen($path, 'w');
fwrite($x, $newfile);
fclose($x);
}

Categories