Я пытаюсь разобрать HTML-таблицу с DOM, и она отлично работает, но когда какая-то ячейка содержит html, она работает неправильно.
Вот пример таблицы HTML
<tr>
<td>Razon Social: </td>
<td>Circulo Inmobiliaria Sur (Casa Central)</td>
</tr>
<tr>
<td>Email: </td>
<td> <img src="[email protected]"/> </td>
</tr>
И PHP Code:
$rows = $dom->getElementsByTagName('tr');
foreach ($rows as $row)
{
$cells = $row->getElementsByTagName('td');
if(strpos($cells->item(0)->textContent, "Razon") > 0)
{
$_razonSocial = $cells->item(1)->textContent;
}
else if(strpos($cells->item(0)->textContent, "Email") > 0)
{
$_email = $cells->item(1)->textContent;
}
}
echo "Razon Social: $_razonSocial<br>Email: $_email";
ВЫВОД:
Razon Social: Circulo Inmobiliaria Sur (Casa Central)
Email:
Электронная почта пуста, она должна быть:
<img src="[email protected]"/>
Я даже попробовал
$cells->item(1)->nodeValue;
вместо
$cells->item(1)->textContent;
Но это тоже не работает. Как я могу заставить его вернуть значение HTML?
Как я уже упоминал, <img src="[email protected]"/>
не является текстом. Это еще один html-объект. Поэтому попробуйте следующее:
if(strpos($cells->item(0)->textContent, "Razon") !== false) {
$_razonSocial = $cells->item(1)->textContent;
} else if(strpos($cells->item(0)->textContent, "Email") !== false) {
$count = 0;
// here we get all child nodes of td.
// space before img-tag is also a child node, but it has type DOMText
// so we skip it.
foreach ($cells->item(1)->childNodes as $child) {
if (++$count == 2)
$_email = $child->getAttribute('src');
}
// now in $_email you have full src value and can somehow extract email
}
Дать id вашей таблице как item_specification
$dom = new DOMDocument();
@$dom->loadHTML($html);
$x = new DOMXPath($dom);
$table = $x->query("//*[@id='item_specification']/tr");
$rows = $table;
foreach ($rows as $row) {
$atr_name = $row -> getElementsByTagName('td')->item(0)->nodeValue;
$atr_val = $row -> getElementsByTagName('td')->item(1)->nodeValue;
}
echo " {$atr_name} - {$atr_val} <br \>";
Его работа прекрасна.