Skip to content
Advertisement

Output HTML table elements separated by commas in PHP

My code strips td elements from an html table and outputs them in a single line.

Here is an html table my code extracts td values from:

<table width="100%"  border="0" cellspacing="1" cellpadding="0" bgcolor="#006699">
<tr align="center" class="tableRow1Font">
<td width="7%">WAITLIST</td>
<td width="5%">91630</td>
<td width="11%">
ACCY <A HREF="http://www.gwu.edu/~bulletin/ugrad/accy.html#2001" target="_blank">2001</A>
</td>
<td width="5%">10</td>
<td width="16%">Intro Financial Accounting</td>
<td width="6%">3.00</td>
<td width="8%"> Zou, Y</td>
<td width="8%"><A HREF="http://www.gwu.edu/~map/building.cfm?BLDG=DUQUES" target="_blank"
>DUQUES</a> 251</td>
<td width="13%">TR<br>09:35AM - 10:50AM</td>
<td width="14%">
01/13/14 - 04/28/14
</td>
<td width="7%">
</td>
</tr>
</table>

My code that takes these td values and outputs them on their own line. Keep in mind this is only one table of many in my .html file. Here is my code:

$html = file_get_html('badm.html');

$str = '';

foreach($html->find('table tr[align="center"]') as $e)
    $str .= strip_tags($e->innertext) . '<br>';
        echo $str;

The output looks like this (each line is a separate table in my badm.html file): Function Output

My question is this: How can I separate each td element with a single comma WHILE keeping them in the same format above (on their own line)?

Advertisement

Answer

$html = file_get_html('badm.html');
$str = '';
foreach($html->find('table tr[align="center"]') as $e)
{
  foreach($e->find('td') as $f)
  {
   $str .= strip_tags($f->innertext) . ',';
  }
$str = trim($str, ",");
$str .= '<br>';
}
echo $str; 
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement