Wrigleys_Extra Wrigleys_Extra - 1 month ago 15
PHP Question

Undefined offset issue in explode

Firstly I apologise for asking a question which must be somewhat rookie or simple, but I cannot seem to find any code that I've researched to solve my problem.

Notice: Undefined offset: 1 in C:\Users\Joshua\Desktop\USBWebserver v8.5\8.5\root\Assignment\Table.php on line 14

This error continues from Offset 1 - 7.

The code that I am currently using to pull the data from the CSV file is as follows:

<?php
$fp = fopen ("quotes.csv","r");
if (!$fp) {echo "<p>Unable to open remote file.</p>"; exit;}
?>
<table>
<tr><th>ID</th> <th>Price</th> <th>Volume </th></tr>
<?php

$i=0;
while (!feof($fp)):
$line = fgets($fp, 2048);
$out[$i] = array($line);

list ($ID, $Price, $StockDate, $StockTime, $Change, $DayHI, $DayLOW, $Volume,) = explode(",", $out[$i][0]);


echo "<tr><td>$ID</td> <td>$Price</td> <td>$StockDate </td><td>$StockTime</td> <td>$Change</td> <td>$DayHI</td> <td>$DayLOW</td> <td>$Volume</td></tr>";
$fp++;
$i++;
endwhile;

?>
</table>
<?php


//echo "<p>".$out[0][0]."</p>";
//echo "<p>".$out[1][0]."</p>";
//echo "<p>".$out[2][0]."</p>";
fclose($fp);
?>


I'm unsure as to how something is undefined as the correct number of values are being called from the CSV.

I understand this isn't a site to teach someone PHP basics but any advice would be appreciated to help solve the problem, I would be appreciative!

Answer

I think you didn't want to +1 on file pointer:

$fp++;

Removing this line should do the trick.

UPDATE:

You should also check fgets if it's not false, because it means end of file:

$line = fgets($fp, 2048);
if($line === false) break;

Fully working example:

<?php
$fp = fopen ("quotes.csv","r");
if (!$fp) {echo "<p>Unable to open remote file.</p>"; exit;}
?>
<table>
<tr><th>ID</th> <th>Price</th> <th>Volume </th></tr>
<?php
$out = array();
$i=0;
while (!feof($fp)):
   $line = fgets($fp, 2048);
   if($line === false) break;
   $out[$i] = array($line);

   list ($ID, $Price, $StockDate, $StockTime, $Change, $DayHI, $DayLOW, $Volume) = explode(",", $out[$i][0]);


   echo "<tr><td>$ID</td> <td>$Price</td> <td>$StockDate </td><td>$StockTime</td> <td>$Change</td> <td>$DayHI</td> <td>$DayLOW</td> <td>$Volume</td></tr>";
   $i++;
endwhile;

?>
</table>
<?php


echo "<p>".$out[0][0]."</p>";
fclose($fp);

Last echo gave me my first string line from .csv.

Comments