php-b-grader
php-b-grader

Reputation: 3315

How to read string line by line from an array

I have an array of text/html files in which the contents are pricing tables.

I want to read in each line, line by line, and process each cell into a database.

I tried this but it doesn't seem to give me the result I am expecting:

$counter=1;
while( $line = explode(PHP_EOL, $attachment[$filename]) ) {
    printStatus( "Line: " . $counter . " « " . $line );
    $counter++;
}

I have tested the data and print $attachment[$filename] outputs the file as expected

The above loop results in the follwing output:

Line: 1 « Array
Line: 2 « Array
Line: 3 « Array
Line: 4 « Array
Line: 5 « Array
Line: 6 « Array
Line: 7 « Array
Line: 8 « Array
Line: 9 « Array

The first few lines of the file look like this:

<!doctype html public "-//w3c//dtd html 4.0transitional//en">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<pre>
<font face="courier new" size=-4>
13/11/13                                           Clocking Productivity Analysis                                           3619
22:46                                    Date Range: 01/11/13 To 13/11/13   Technician Only                                 Page   1

Tech  Name                Open   Clock   Close   Avail    Sold      Sold    Cost      Cost    Labour  Margin   Docs  Unprod  Sold /
                  Rate     WIP     Hrs     WIP     Hrs     Hrs       Amt     Hrs       Amt     Gross       %            Hrs  Avail%
----  ----------------  ------  ------  ------  ------  ------  --------  ------  --------  --------  ------  -----  ------  ------

Upvotes: 0

Views: 1094

Answers (2)

deceze
deceze

Reputation: 522076

while ($line = explode(PHP_EOL, $attachment[$filename]))

Let's analyse this:

  • explode returns an array, so $line is an array, not an element of the array
  • $line = explode(...) gets executed again and again every time the while condition is evaluated, meaning on every single loop iteration you're exploding the string again and assigning a fresh array to $line

You either want:

$lines = explode(PHP_EOL, $attachment[$filename]);
while ($line = array_shift($lines))

or

foreach (explode(PHP_EOL, $attachment[$filename]) as $line)

Upvotes: 2

u_mulder
u_mulder

Reputation: 54831

Currently $line is array. If you want to print current element in $line defined by $counter use this:

echo $line[$counter];

Or use file function, it will return array too.

Upvotes: 1

Related Questions