I have a text file as Name1,9999999,123 Name2,8888888,456 Name3,7777777,426 I want to create sentences in PHP like Mr Name1 , your number is 9999999 and value is 123. Mr Name2 , your number is 8888888 and value is 426. How to do it using PHP ? I was trying : $row = 1; $handle = fopen("data.txt", "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $num = count($data); $row++; for ($c=0; $c < $num; $c++) { $Name = $data[$c] . "<br />\n"; $key = $data[$c]; } } fclose($handle); Code (markup): But couldnt. Please help.
First understand what this code does. If you look at the $data array for each line you will get a value of Array ( [0] => Name1 [1] => 9999999 [2] => 123 ) Code (markup): For the first row, for example. So you have three elements there. Your for loop is looping through all three of them. So anything you print will be duplicated three times. Since you already know what the number of elements is. The easiest way is to call each array element. For example: print "Mr $data[0] , your number is $data[1] and value is $data[2].\n"; Code (markup): No need for the internal for loop.
This might be an easy way <?php $data = 'Name1,9999999,123 Name2,8888888,456 Name3,7777777,426'; $data = explode ( "\n", $data ); foreach ( $data as $d ) { $dd[] = explode ( ',', $d ); } print_r ( $dd ); ?> PHP: and output is Array ( [0] => Array ( [0] => Name1 [1] => 9999999 [2] => 123 ) [1] => Array ( [0] => Name2 [1] => 8888888 [2] => 456 ) [2] => Array ( [0] => Name3 [1] => 7777777 [2] => 426 ) ) Code (markup): Find a way and work around it then
Using explode works, but not really the optimal way. It's like using a wrench to get out a screw. Fgetcsv is a built in function to read CSV files. So you would want to use that as it is made to read CSV files.
Lots of ways to do this, but this is probably the easiest: <?php $handle = fopen('test.txt', 'r'); while ($line = fgetcsv($handle)) { echo 'Mr ' . $line[0] . ', your number is ' . $line[1] . ' and value is ' . $line[2] . '.'; } Code (markup):
You can read file line by line and use explode function to convert line into array and then use implode function to combine again in your required format