James
James

Reputation: 262

fgets and in_array not working together correctly

I am working on a project where filtered text file data is imported into an SQL database line by line. The importation of the data is functioning correctly, but the filtering feature that is not functioning. In troubleshooting I created the below code to see what is going on.

$excludeLines = array("Doc #:", 'Title:');

$tempFile = "./temp/" . $_FILES["certFile"]["name"];
    if (move_uploaded_file($_FILES["certFile"]["tmp_name"],  $tempFile)) {
        $importData = fopen($tempFile, "r");
        while(($line=fgets($importData))!==false) {
            if(trim($line) != '' && $line != NULL) {
                if(in_array($line, $excludeLines)) {
                    echo 'Included: ';
                } else {
                    echo 'Not included: ';
                }
                echo $line . "<br>";
            } 
        }
        fclose($importData);
    }

The result is: Not included: Doc #:

What I want to see: Included: Doc #:

If anyone can point me in the correct direction, it would be greatly appreciated.

Upvotes: 0

Views: 26

Answers (1)

nosurs
nosurs

Reputation: 665

fgets includes the line endings, so you need to either include them in your lookup array as well...

$excludeLines = array("Doc #:\n", "Title:\n"); // Assuming Unix-like line endings

...or strip them when matching:

in_array(trim($line), $excludeLines)

Upvotes: 1

Related Questions