2013-11-14 2 views
0

Я пытаюсь разобрать таблицу HTML с DOM, и она отлично работает, но когда какая-либо ячейка содержит html, она не работает должным образом.PHP DOM nodeValue не работает

Вот пример 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 код:

$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: 

Email пуст, оно должно быть:

<img src="[email protected]"/> 

Я даже попытался

$cells->item(1)->nodeValue; 

вместо

$cells->item(1)->textContent; 

Но это тоже не работает. Как я могу заставить его вернуть значение HTML?

+0

Определите, что «не работает должным образом». Любая ошибка? – Raptor

+0

Нет ошибки, она ничего не возвращает. Просто пусто. – Azeem

+0

Этот вар не пуст? $ _email уверены? –

ответ

0

Дайте идентификатор к столу, как 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 \>"; 

его рабочих штрафа.

0

Как я уже говорил, <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 
} 
Смежные вопросы