1

I've got a problem where I'm trying to read a text file like this:

Joe
Johnson

Linus
Tourvalds

and while parsing it in php, I need to be able to detect the newlines. I'm trying to correctly define $newline. I'm looping through the array of lines in the $file variable.

while($line = next($file))
    if($line = $newline)
        echo "new line";

The problem is that I can't seem to match the newline character. I know that it is actually showing up in the $file array, because this:

while($line = next($file))
    echo $line;

outputs the file verbatim, with newlines and all. I've already tried "\n", " ", and I'm not sure what to try next. A little help?

3
  • 1
    "I'm looping through the array of lines" So you already have the lines of the file split up? Commented Feb 11, 2011 at 1:43
  • Exactly. How did you get the $file array in the first place. And why are you using next() instead of a standard foreach/for? (there are reasons, but not too many)... Commented Feb 11, 2011 at 1:47
  • careful using next(), it advances the pointer before returning the element! (you'll miss "joe"). Commented Feb 11, 2011 at 4:20

3 Answers 3

1
$file = file("path/to/file.txt");

// Incase you need to call it multiple times ...
function isNewLine($line) {
    return !strlen(trim($line));
}

foreach ($file as $line) {
    if (isNewLine($line)) {
        echo "new line<br/>";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Maybe something like this would work for you?

while($line = next($file)) {
    if(in_array($line, array("\r", "\n", "\r\n"))) {
        echo "new line";
    }
}

Comments

0

I think this solution may help you guys. This works if you are parsing csv that is generated from Mac or windows. Reading csv with multilines created in Mac, gives problem i.e. you cannot read each line in a loop but all csv data is read as single line.

This problem is solved by following solution:

//My CSV contains only one column
$fileHandle = fopen("test.csv",'r');
$codesArray    = array();
count = 0;
while (!feof($fileHandle) ) {
$line = fgetcsv($fileHandle);
if($line[0]!="") {
   $data = str_replace("'", "", (nl2br ($line[0])));
   $dataArray = explode('<br />' ,$data );
   foreach($dataArray as $data) {
       $codesArray[] = trim($data);
   }
}
}
echo "<pre>";
print_r($codesArray);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.