Why is str_replace not working correctly - php

In my directory I have a list.csv of the form:
RP2015, active
Hope, paused
Process99, active
I'm writing a php script to allow a web user to switch the different lines from 'active' to 'paused' and back. Unfortunately I've hit a snag. My current code is live at: http://whitewaterwriters.com/Driver/index.php
and it looks like this
<HTML>
<Body>
<?
if ($_POST != null) {
$target = $_POST ['sprint'];
echo "<br>Target was:".$target;
$replacement=str_replace('active','paused',$target);
if (strpos($target,'paused') !== false) {
$replacement=str_replace('paused','active',$target);
}
echo "<br>Replacement was:".$replacement."<br>";
$filename = "list.csv";
$contents = file_get_contents($filename);
print "<br>contents was:".$contents;
$new_contents = str_replace($target, $replacement, $contents);
print "<br>contents became:".$new_contents;
file_put_contents($filename, $new_contents);
}
?>
<br><br>
<?php
$row = 1;
if (($handle = fopen("list.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
echo '<form action="index.php" method=post>';
echo $data[0] . $data[1];
echo '<button type="submit" value="'. $data[0].", ".$data[1].'" name="sprint">Pause</button></form><br>';
}
fclose($handle);
}
?>
</body>
</html>
For some reason the replace is not firing. The event is captured, the correct target and replace strings are (I think) generated, but the replace is NOT coming out. The output I get is:
Target was:RP2015, active
Replacement was:RP2015, paused
contents was:RP2015, active
contents became:RP2015, active
RP2015 active
Can anyone tell me what's going on?
EDIT:
The current list.csv is exactly:
RP2015, active
`

Try this:-
$fp = fopen($filename, "wb");
$handle = fopen($filename, "wb");
$replacement = str_replace("active", "paused", $fp);
$numbytes = fwrite($handle, $replacement);
fclose($handle);

The thing I had forgotten is that html squashes consecutive spaces together which is why the $target looked like it was fine. Actually:
$data[0].", ".$data[1]
only needed to be
$data[0].",".$data[1]
Because there was a space left over from the csv parsing. I'll make the code a bit more robust to that in future.
For the interested - this helper function I wrote helped me locate the error:
function toask($inStr){
$arr1 = str_split($inStr);
foreach ( $arr1 as $a){
print ord($a)." ";
}
}
It converts a string to a sequence of ascii codes do you can make sure, for example, that quote characters are the ones you think they are...

Related

put echo into a variable with php

I'm having troubles with a function that create html from a csv file with php functions fgetcsv() and echo.
Here's the code:
<?php function getContent($data) {
if (($handle = fopen($data, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
echo <p>...</p>
}
}
} ?>
It outputs an html table and then, I would like to use this with the function fwrite() to write it into a new html file that I just created. Now, I just tried to use it as a variable like this:
$content = getContent($data);
fwrite($file, $content);
But it's not working... Any idea ?
P.S: I have a lot of echo in the getContent function, this is why I don't want to use a variable.
(disclaimer: I understand your current function does echo what you want, so I'm assuming your echo-line is modified for this example, and it contains something with that $data in real,right?)
Echo prints to screen, and you don't want that, so save it and return it as a string.
quick example:
function getContent($data) {
$result = ""; //you start with an empty string;
if (($handle = fopen($data, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$result .= "<p>...</p>"; //add what you used to echo to the string
}
}
return $result; //send your string back to the caller of the function
}
now you can call that function and do stuff with your string. First, test it with echo:
$content = getContent($data); //gets you the data in a string
echo $content; //echoes it, just like you did before.
if that works and you have something you can write your content to (that $file must be defined obviously, you can do what you did:
$content = getContent($data); //still gets you the data
fwrite($file, $content); //writes it to a file.
Now, if the write doesn't work, you should debug that first with a string you hardcode, but that hasn't got much todo with the issue in this question.
I eventually changed my echo with a variable $text that I concatenated like this $text .= "<p>...</p>"
Afterwards, I just needed to use this variable to create the html file.

How can I get the total number of rows in a CSV file with PHP?

Using PHP, how can I get the total number of rows that are in a CSV file? I'm using this method but cannot get it to work properly.
if (($fp = fopen("test.csv", "r")) !== FALSE) {
while (($record = fgetcsv($fp)) !== FALSE) {
$row++;
}
echo $row;
}
Create a new file reference using SplFileObject:
$file = new SplFileObject('test.csv', 'r');
Try to seek to the highest Int PHP can handle:
$file->seek(PHP_INT_MAX);
Then actually it will seek to the highest line it could in the file, there is your last line and the last line + 1 is equals to your total lines:
echo $file->key() + 1;
Tricky, but this will avoid you from loading the file contents into memory, which is a very cool thing to do when dealing with really large files.
Here's another option using file() to read the entire file into an array, automatically parsing new lines etc:
$fp = file('test.csv');
echo count($fp);
Also, since PHP5, you can pass in the FILE_SKIP_EMPTY_LINES... to skip empty lines, if you want to:
$fp = file('test.csv', FILE_SKIP_EMPTY_LINES);
Manual: http://php.net/manual/en/function.file.php
Try
$c =0;
$fp = fopen("test.csv","r");
if($fp){
while(!feof($fp)){
$content = fgets($fp);
if($content) $c++;
}
}
fclose($fp);
echo $c;
I know that this is pretty old, but actually I ran into the same question.
As a solution I would assume to use linux specific logic:
$rows = shell_exec('$(/bin/which cat) file.csv | $(/bin/which tr) "\r" "\n" | $(which wc) -l');
NOTE: this only works for linux only and this only should be used if you are 100% certain that your file has no multiline-cells
CSV rows are separated by line breaks. Therefore, split the rows by line breaks, and you will get an array of rows, which is countable.
if (($fp = fopen("test.csv", "r")) !== FALSE) {
$rows = explode("\n", $fp);
$length = count($rows);
echo $length;
}
Note; none of higher-upvoted solutions that count lines in the file are reliable, as they are only counting the lines, not the csv entries (which can contain newline characters)
I'm using a similar solution to op, and it works perfectly, but with op's code the while part can break on empty lines, which is potentially his problem.
So it looks like this (edited op's code)
$rowCount=0;
if (($fp = fopen("test.csv", "r")) !== FALSE) {
while(!feof($fp)) {
$data = fgetcsv($fp , 0 , ',' , '"', '"' );
if(empty($data)) continue; //empty row
$rowCount++;
}
fclose($fp);
}
echo $rowCount;
I find this the most reliable:
$file = new SplFileObject('file.csv', 'r');
$file->setFlags(
SplFileObject::READ_CSV |
SplFileObject::READ_AHEAD |
SplFileObject::SKIP_EMPTY |
SplFileObject::DROP_NEW_LINE
);
$file->seek(PHP_INT_MAX);
$lineCount = $file->key() + 1;
I know this is an old post, but I've been googling this issue, and found that the only problem with the original code was that you need to define $row outside the while loop, like this:
if (($fp = fopen("test.csv", "r")) !== FALSE) {
$row = 1;
while (($record = fgetcsv($fp)) !== FALSE) {
$row++;
}
Just in case it helps someone :)
echo $row;
}
In case you are getting the file from a form
$file = $_FILES['csv']['tmp_name'];
$fp = new SplFileObject($file, 'r');
$fp->seek(PHP_INT_MAX);
echo $fp->key() + 1;
$fp->rewind();
Works like charm!!!!!!!!!!!!!!!!!!
$filename=$_FILES['sel_file']['tmp_name'];
$file=fopen($filename,"r");
$RowCount=0;
while ((fgetcsv($file)) !== FALSE)
{
$RowCount++;
}
echo $RowCount;
fclose($file);

Preg_match to match phone number

I have a csv file with about 2000 websites in it, I have a script working that file_get_contents of each site, and looks for a phone number.
My preg match is not working!!??
I need to find the exact number string 800-885-7505
I tried:
preg_match('/^800-885-7505$/', $page, $matches);
But didnt work.... Can anyone tell me why?
Thank you!
I tried:
<?
$file = fopen('file.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
$page = file_get_contents("http://www.".$line[0]);
preg_match('/800-885-7505/', $page, $matches);
echo "http://www.".$line[0]." = ".$matches[1] . "<br><br>";
}
fclose($file);
?>
This DID work, I have the same script looking for what iframe is on a page, and it works great:
<?
$file = fopen('file.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
$page = file_get_contents("http://www.".$line[0]);
preg_match('/<iframe.*src=\"(.*)\".*><\/iframe>/isU', $page, $matches);
if (($matches[1]!=="http://www.url.com/lmapp.html") && ($matches[1]!=="http://www.url.com/mc_NewApp2.html"))
{echo "http://www.".$line[0]." = ".$matches[1] . "<br><br>";}
}
fclose($file);
?>
So I thought I all needed to do was get a correct preg-match for the phone number
You can use:
preg_match('/800-885-7505/', $page, $matches);
or faster:
if ( strpos('800-885-7505',$page) !== false )

Replace a particular line in a text file using php?

I have a text file that stores lastname, first name, address, state, etc as a string with a | delimiter and each record on a separate line.
I have the part where I need to store each record on a new line and its working fine; however, now I need to be able to go back and update the name or address on a particular line and I can't get it to work.
This how to replace a particular line in a text file using php? helped me here but I am not quite there yet. This overwrites the whole file and I lose the records. Any help is appreciated!
After some edit seems to be working now. I am debugging to see if any errors.
$string= implode('|',$contact);
$reading = fopen('contacts.txt', 'r');
$writing = fopen('contacts.tmp', 'w');
$replaced = false;
while (!feof($reading)) {
$line = fgets($reading);
if(stripos($line, $lname) !== FALSE) {
if(stripos($line, $fname) !== FALSE) {
$line = "$string";
$replaced = true;
}
}
fwrite($writing, "$line");
//fputs($writing, $line);
}
fclose($reading); fclose($writing);
// might as well not overwrite the file if we didn't replace anything
if ($replaced)
{
rename('contacts.tmp', 'contacts.txt');
} else {
unlink('contacts.tmp');
}
It seems that you have a file in csv-format. PHP can handle this with fgetcsv() http://php.net/manual/de/function.fgetcsv.php
if (($handle = fopen("contacts.txt", "r")) !== FALSE) {
$data = fgetcsv($handle, 1000, '|')
/* manipulate $data array here */
}
fclose($handle);
So you get an array that you can manipulate. After this you can save the file with fputcsv http://www.php.net/manual/de/function.fputcsv.php
$fp = fopen('contacts.tmp', 'w');
foreach ($data as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
Well, after the comment by Asad, there is another simple answer. Just open the file in Append-mode http://de3.php.net/manual/en/function.fopen.php :
$writing = fopen('contacts.tmp', 'a');

CSV file read fail (PHP )

I am trying to read a CSV file (delimited by commas) but unfortunately, it isn't responding as it ought to. I am not so sure what I am doing wrong here, but I'll paste out the contents of the code and the CSV file both :
$row = 0;
if($handle = fopen("SampleQuizData.csv","r") !== FALSE)
{
// WORKS UNTIL HERE, SO FILE IS BEING READ
while(!feof(handle))
{
$line = fgetcsv($handle, 1024, ",") ;
echo $line[2]; // DOES NOT WORK
}
}
Here is the CSV file: (the emails and names have been changed here to protect the identities of the users)
parijat,something,parijatYkalia#hotmail.com
matthew,durp, mdurpdurp#gmail.com
steve,vai,stevevai#gmail.com
rajni,kanth,rajnikanth#superman.com
it lacks a '$' to the handle variable
while(!feof($handle)){
and not :
while(!feof(handle)){
Give this a try:
<?php
$row = 0;
if (($handle = fopen("SampleQuizData.csv", "r")) !== FALSE)
{
while(!feof($handle))
{
$line = fgetcsv($handle, 1024, ",") ;
echo "$line[2]";
}
}
?>
It's worth a mention but when I was working on CSV exports a few weeks ago, I had weird line ending inconsistencies. So I put this at the top of my php file and it worked splendid.
<?php
ini_set("auto_detect_line_endings", true);
?>

Categories