How to read line by line in php

后端 未结 5 1243
北荒
北荒 2021-01-06 11:21

when i try to insert each line into my oracle database i get an error stating invalid number, but if have only one line in the file it works fine.

$file = @f         


        
相关标签:
5条回答
  • 2021-01-06 11:40

    Your explode() call is using 9 spaces as a separator, but your file only appears to have 5 spaces between each number. This means your $currentline be a single element array containing the original line, and not separate elements with a number in each.

    Either change the number of spaces in the explode call, or change to

    $currentLine = preg_split('/\s+/', $currentLine);
    

    which will split on any number of sequential spaces.

    0 讨论(0)
  • 2021-01-06 11:54

    Try this:

    $currentLine = trim(fgets($file)); 
    

    It's possibly failing on the newline/carriage-return at the end of the line.

    If not, where is this insert() function defined? Build a debug section that echos or writes out the attempted queries so you can really see the issue.

    0 讨论(0)
  • 2021-01-06 11:54
    $lines = explode("\n", str_replace("\r", "", file_get_contents("file.text")));
    
    foreach ($lines as $line)
    {
         insert(explode('        ', $line);
    }
    
    0 讨论(0)
  • 2021-01-06 11:54

    try this :

    // Read all data in the file
    $file_all = file_get_contents('file.text') or die("unable to open file");
    // create an array with each index = a line
    $file_lines = explode(chr(13),$file_all);
    // Insert each line found
    foreach ($file_lines as $file_line) { insert($file_line); };
    
    0 讨论(0)
  • 2021-01-06 11:59

    I would double check that there is not a new line at the end of the file. Maybe even double check inside of php that the line read is not blank.

    $lineCount=0;
    // while there is another line to read in the file
    while (!feof($file))
    {
        $lineCount++;
        // Get the current line that the file is reading
        $currentLine = fgets($file);
        if(trim($currentLine) != ''){
            $currentLine = explode('        ',$currentLine) ;
            insert($currentLine) ;
            echo "Inserted line number $lineCount<br />";
        } else {
            echo "There was a blank line at line number $lineCount.<br />";
        }
    } 
    
    0 讨论(0)
提交回复
热议问题