Search code examples
phpcsvfopenfgetcsv

Incorrect String Length While Reading A CSV File Using PHP


I am reading a CSV file, line by line using following php code.

<?php
$temp=0;
$s="http://localhost/BulkMessage/Uploads/Number_Files/f7aa248e5fce52411723_CSV_7xxxxxxxx.csv";
try
{
    $file = fopen($s, 'r');
} catch (Exception $ex) {
    $_SESSION['error']="Can't read the file";
    header('Location: '.'../view_sending_rich_message.php');
}
while (($line = fgetcsv($file)) !== FALSE)
{
    echo $line[0]." Length: ".strlen($line[0])."<br>";
}

?>

Reading process works as expected, but when I try to print the length of a line it shows some abnormal behavior. These are few sample lines from my CSV.

  1. 71455169311
  2. 71455169112222100

For both of these lines, the string length is shown as 11. For the first one it is correct, but second one has 16 characters. It seems that for any value which has more than 11 characters, string length is shown as 11 (When strlen is used) . Below shows the out of my php script for above 2 lines.

71455169311 Length: 11
7.14552E+16 Length: 11

Is there any way to get the string length correctly? What is the reason for this behavior? Thanks


Solution

  • It seems that fgetcsv can return integers / floats, not only strings. If the exact numbers are required, than I don't know if fgetcsv can also return everything as a string, but if only the length of the string is required, you can use strlen(number_format($line[0], 0, '.', '')) (this is assuming the numbers have no decimals).