Работа с DOMXpath

Товарищ попросил распарсить html генерируемый php
<div class="reports">
         <div class="ERROR">
           <div class="name">5555</div>
           <div class="author">6666</div>
         </div>
         <div class="SUCCESS">
           <div class="name">444</div>
           <div class="author">777</div>
         </div>
         <div class="SUCCESS">
           <div class="name">888</div>
           <div class="author">999</div>
         </div>
         <div class="ERROR">
           <div class="name">000</div>
           <div class="author">111</div>
         </div>
         <div class="SUCCESS">
           <div class="name">333</div>
           <div class="author">222</div>
         </div>
     </div>
  1. $doc = '
  2.    <div class="reports">
  3.        <div class="ERROR">
  4.            <div class="name">5555</div>
  5.            <div class="author">6666</div>
  6.        </div>
  7.        <div class="SUCCESS">
  8.            <div class="name">444</div>
  9.            <div class="author">777</div>
  10.        </div>
  11.        <div class="SUCCESS">
  12.            <div class="name">888</div>
  13.            <div class="author">999</div>
  14.        </div>
  15.        <div class="ERROR">
  16.            <div class="name">000</div>
  17.            <div class="author">111</div>
  18.        </div>
  19.        <div class="SUCCESS">
  20.            <div class="name">333</div>
  21.            <div class="author">222</div>
  22.        </div>
  23.    </div>
  24. ';
  25.  
  26.  
  27. $dom = new DOMDocument();
  28. $dom->loadHTML($doc);
  29.  
  30. $xpath = new DOMXpath($dom);
  31. $elements = $xpath->query( '//div[@class="reports"]/div');
  32.  
  33. $result = [];
  34.  
  35. foreach ($elements as $k => $element) {
  36.     foreach ($element->getElementsByTagName('div') as $item) {
  37.         $result[$element->getAttribute('class')][$item->getAttribute('class')][] = $item->textContent;
  38.     }
  39. }
  40.  
  41. echo '<pre>' . print_r($result, true) . '</pre>';
Вывод
Array
(
     [ERROR] => Array
         (
           [name] => Array
           (
           [0] => 5555
           [1] => 000
           )
           [author] => Array
           (
           [0] => 6666
           [1] => 111
           )
         )

     [SUCCESS] => Array
         (
           [name] => Array
           (
           [0] => 444
           [1] => 888
           [2] => 333
           )
           [author] => Array
           (
           [0] => 777
           [1] => 999
           [2] => 222
           )
         )
)

Реклама

Мы в соцсетях

tw tg yt gt