простой HTML-анализатор DOM найти текст - PullRequest
0 голосов
/ 05 ноября 2019

В моем случае страницы имеют несколько table с тем же классом, поэтому я нахожу значение с помощью tr, td and plaintext.

PHP Part:

$html = file_get_html('http://www.example.com/');
$eles = $html->find('.info-tab');
foreach($eles as $e) {
    if(strpos($e->find('tr',0)->plaintext, "Information about the manufacturer and the model." ) ) {
    $value1 = $e->find('td',1)->plaintext;
    }

    if(strpos($e->find('tr',1)->plaintext, "Information about the manufacturer and the model." ) ) {
    $value2 = $e->find('td',1)->plaintext;
    }
}
echo $value1;
echo $value2;

Веб-страница

// Here's will be many other "Table" with diffrent text but class & ID are same...

<table class="info-tab">
    <tbody>
        <tr>
            <td>Information about the manufacturer and the model.</td>
            <td>1000</td>
        </tr>
        <tr>
            <td>dummy text</td>
            <td>dummy text</td>
        </tr>
    </tbody>
</table>

// Here's will be many other "Table" with diffrent text but class & ID are same...

<table class="info-tab">
    <tbody>
        <tr>
            <td>dummy text</td>
            <td>dummy text</td>
        </tr>
        <tr>
            <td>Information about the manufacturer and the model.</td>
            <td>3000</td>
        </tr>
        <tr>
            <td>dummy text</td>
            <td>dummy text</td>
        </tr>
    </tbody>
</table>

// Here's will be many other "Table" with diffrent text but class & ID are same...

Страница содержит несколько таблиц 20 плюс, только две таблицы имеют этот текст, поэтому я хочу их скопировать.

Как найтиэти два значения?

1 Ответ

1 голос
/ 05 ноября 2019

Вы должны выполнять итерации таблиц, и для каждой таблицы повторять строки:

$token = "Information about the manufacturer and the model.";
$tables = $html->find('.info-tab');
$values = [];
foreach ($tables as $table) {
    foreach ($table->find('tr') as $row) {
        if (strpos($row->find('td', 0)->plaintext, $token) !== false) {
            $values [] = $row->find('td', 1)->plaintext;
        }
    }
}
var_dump($values);

Ваш код не работает, потому что $e->find('td', 1) всегда является вторым значением td первой строки в таблице (и этоне считает выбранную строку 0 или 1).

...