Here is the sample html:
$html = '<table>
<tbody>
<tr>
<td><span style="background-color: #f1c40f;">Cell 1</span></td>
<td>Cell 2</td>
</tr>
</tbody>
</table>';
Target is to retrieve everything between "td" tags, including the "span" tag, if any. Here is the expected result:
<span style="background-color: #f1c40f;">Cell 1</span>
Cell 2
I tried to use DOMDocument()->getElementsByTagName("td")->saveHTML() and nodeValue without success.
Here is the php code I tried:
$html = '<table>
<tbody>
<tr>
<td><span style="background-color: #f1c40f;">Cell 1</span></td>
<td>Cell 2</td>
</tr>
</tbody>
</table>';
$doc = new DOMDocument();
$doc->loadHTML('<?xml encoding="utf-8" ?>' . $html);
$tds = $doc->getElementsByTagName("td");
foreach($tds as $td){
dump('saveHTML: '.$doc->saveHTML($td));
dump('nodeValue: '.$td->nodeValue);
}
die();
Here is the outputs:
^ "saveHTML: <td><span style="background-color: #f1c40f;">Cell 1</span></td>"
^ "nodeValue: Cell 1"
^ "saveHTML: <td>Cell 2</td>"
^ "nodeValue: Cell 2"
Did I do anything wrong? Thanks a lot!
My Answer:
Rate this post
4 of 5 based on 3561 votesComments