2

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

3
  • 1
    Loooks like the line with the longer number is being presented to you in the format you are printing which is 11 chars Commented Jan 8, 2020 at 13:10
  • 1
    Is this Q&A any help stackoverflow.com/questions/22647042/… Commented Jan 8, 2020 at 13:12
  • 2
    @RiggsFolly Now, I know the reason for that behavior. I used excel to create the csv and it seems that excel is reformatting numbers a scientific format. Thank You. Commented Jan 8, 2020 at 16:29

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

In my case, csv contains telephone numbers.So, there is no issue arising due to decimals. Your answer is doing the job for me. Thank you very much.
As @RiggsFolly Suggested, following Q&A shows the reason. stackoverflow.com/questions/22647042/…
0

Instead of strlen() try using mb_strlen().

1 Comment

I tried it. But it gives the same result as strlen(). It seems that there is nothing to with stren(), excel is reformatting numbers in scientific notation.Thanks for your response.

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.