Проблема зацикливания Xpath для анализа простой таблицы HTML в массиве php - PullRequest
0 голосов
/ 27 февраля 2019

Итак, мой предыдущий вопрос: PHP Преобразование HTML-таблицы в JSON был быстро отклонен как дубликат, и я все еще пытаюсь найти то, что мне нужно.Я думаю, что это в основном логическая проблема в циклах, и мне нужен кто-то еще, чтобы взглянуть на это.

Учитывая эту таблицу в качестве примера:

<table id="Details" class="DATA_TABLE DATA_TABLE_WO_TOTAL">
  <tr>
    <th>Application</th>
    <th>Version number</th>
    <th>Virtual Administration Server</th>
    <th>Group</th>
    <th>Device</th>
    <th>Installed</th>
    <th>Last visible time</th>
    <th>Last connection to Administration Server</th>
    <th>IP address</th>
  </tr>
  <tr>
    <td class="sD">some text</td>
    <td class="sD">10.2.5.3201</td>
    <td class="sD"></td>
    <td class="sD">Thin PC</td>
    <td class="sD">PC#</td>
    <td class="sD">date</td>
    <td class="sD">date</td>
    <td class="sD">date</td>
    <td class="sD">ip address</td>
  </tr>
  <tr>
     <tr>
    <td class="sD">some more text</td>
    <td class="sD">10.2.5.3201</td>
    <td class="sD"></td>
    <td class="sD">Thin PC</td>
    <td class="sD">PC#</td>
    <td class="sD">date</td>
    <td class="sD">date</td>
    <td class="sD">date</td>
    <td class="sD">ip address</td>
  </tr>
</table>

Мне нужно создать массив (который я позже смогу преобразовать в json), в котором теги th - это ключи, а затем все теги td внутри друг друга.данные, соответствующие этим ключам.У меня есть следующий код php:

<?php
$dom = new DOMDocument;
$dom->loadHTML($cleantable2); //this is the table above
$xpath = new DOMXPath($dom);

foreach($xpath->query('//table/tr') as $tr){
        $tmp = [];
                foreach($xpath->query('//table/tr/th', $tr) as $th){
                        $key = $th->textContent;
                        foreach($xpath->query('td', $tr) as $td){
                                $tmp[$key] = trim($td->textContent);
                        }
                }
                $result[]=$tmp;
        }
var_dump($result);

?>

Он правильно понимает ключи, но не данные, пример вывода:

  [89]=>
  array(9) {
    ["Application"]=>
    string(13) "192.168.6.104"
    ["Version number"]=>
    string(13) "192.168.6.104"
    ["Virtual Administration Server"]=>
    string(13) "192.168.6.104"
    ["Group"]=>
    string(13) "192.168.6.104"
    ["Device"]=>
    string(13) "192.168.6.104"
    ["Installed"]=>
    string(13) "192.168.6.104"
    ["Last visible time"]=>
    string(13) "192.168.6.104"
    ["Last connection to Administration Server"]=>
    string(13) "192.168.6.104"
    ["IP address"]=>
    string(13) "192.168.6.104"
  }

Как видите, он выбирает только IP-адрес для каждого ключа, а не остальные данные.Что я делаю неправильно?Может кто-то помочь, а не просто отклонить это как дубликат?Я пытался выяснить это в течение более чем одного дня, я почти уверен, что моя проблема просто не работает правильно, но я ее не вижу ...

Спасибо

1 Ответ

0 голосов
/ 27 февраля 2019
$strhtml='
<table id="Details" class="DATA_TABLE DATA_TABLE_WO_TOTAL">
  <tr>
    <th>Application</th>
    <th>Version number</th>
    <th>Virtual Administration Server</th>
    <th>Group</th>
    <th>Device</th>
    <th>Installed</th>
    <th>Last visible time</th>
    <th>Last connection to Administration Server</th>
    <th>IP address</th>
  </tr>
  <tr>
    <td class="sD">some text</td>
    <td class="sD">10.2.5.202</td>
    <td class="sD">Plato</td>
    <td class="sD">Thin PC</td>
    <td class="sD">PC#</td>
    <td class="sD">date a</td>
    <td class="sD">date b</td>
    <td class="sD">date c</td>
    <td class="sD">10.25.100.1</td>
  </tr>
  <tr>
     <tr>
    <td class="sD">some more text</td>
    <td class="sD">10.2.5.321</td>
    <td class="sD">Socrates</td>
    <td class="sD">Thick PC</td>
    <td class="sD">PC#</td>
    <td class="sD">date x</td>
    <td class="sD">date y</td>
    <td class="sD">date z</td>
    <td class="sD">10.25.100.2</td>
  </tr>
</table>';

Учитывая приведенный выше фрагмент HTML, возможно, следующее делает то, что вам нужно?Комментарии должны помочь увидеть, что я сделал

libxml_use_internal_errors( true );
$dom=new DOMDocument;
$dom->loadHTML( $strhtml );
libxml_clear_errors();

$xp=new DOMXPath( $dom );
/* find the `th` elements */
$col = $xp->query( '//tr/th' );

/* temp arrays */
$tmp=$out=$keys=array();


if( $col->length > 0 ){
    /* get all headers as keys */
    foreach( $col as $node )$keys[]=$node->nodeValue;

    /* get all table cell data - store in single array */
    $col=$xp->query( '//tr/td[ @class="sD" ]' );
    foreach( $col as $node )$tmp[]=$node->nodeValue;

    /* split data into chunks according to number of columns */
    $rows=array_chunk( $tmp, count( $keys ) );

    /* combine keys and chunks */
    foreach( $rows as $row ){
        $tmp=array();
        foreach( $row as $i => $value ) $tmp[ $keys[ $i ] ]=$value;
        $out[]=$tmp;
    }

    echo json_encode( $out );
}

вывод:

[
    {
        "Application":"some text",
        "Version number":"10.2.5.202",
        "Virtual Administration Server":"Plato",
        "Group":"Thin PC",
        "Device":"PC#",
        "Installed":"date a",
        "Last visible time":"date b",
        "Last connection to Administration Server":"date c",
        "IP address":"10.25.100.1"
    },
    {
        "Application":"some more text",
        "Version number":"10.2.5.321",
        "Virtual Administration Server":"Socrates",
        "Group":"Thick PC","Device":"PC#",
        "Installed":"date x",
        "Last visible time":"date y",
        "Last connection to Administration Server":"date z",
        "IP address":"10.25.100.2"
    }
]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...