Работа с 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>
<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>
- $doc = '
- <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>
- ';
- $dom = new DOMDocument();
- $dom->loadHTML($doc);
- $xpath = new DOMXpath($dom);
- $elements = $xpath->query( '//div[@class="reports"]/div');
- $result = [];
- foreach ($elements as $k => $element) {
- foreach ($element->getElementsByTagName('div') as $item) {
- $result[$element->getAttribute('class')][$item->getAttribute('class')][] = $item->textContent;
- }
- }
- 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
)
)
)
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
)
)
)