▽1
●
a-kuma3 ●300ポイント ベストアンサー |
前の質問の回答のコードを手直ししてみました。
<?php require "simple_html_dom.php"; $html = ... function text_content($e) { $s = ''; while ($e != null && preg_match('/^H[1234]/i', $e->tag)) { $s = $e->plaintext . ($s == '' ? '' : ' & ') . $s; $e = $e->prev_sibling(); } return $s; } function printout($breadcrumb, $bottom_content, $n) { echo $n . '.[Subject]:' . implode(' > ', array_map("text_content", $breadcrumb)) . '<br>'; echo $n . '.[Contents]:' . $bottom_content->plaintext . '<br>'; } $n = 1; $ul_list = $html->find('UL'); foreach ($ul_list as $ul) { $ul_child = $ul->find('UL'); if (count($ul_child) == 0) { $li_list = $ul->find('LI'); foreach ($li_list as $item) { $bottom_content = $item; $route = array(); $limit = 100; while ($item->tag == 'li') { $limit = $limit - 1; $p = $item->parent(); // 多分 UL if ($p->tag == "body") { // 念のため break; } // UL の前にある要素 $e = $p->prev_sibling(); // もし、あれば、多分 H* if ($e) { if (preg_match('/^H[1234]/i', $e->tag)) { $route[] = $e; } // なければ、TABLE の中かも } else { // TABLE まで上に向かう $e = $p->parent(); while ($e->tag != "table") { $e = $e->parent(); } // TABLE の前にある要素 $e = $e->prev_sibling(); // 多分、H* if (preg_match('/^H[1234]/i', $e->tag)) { $route[] = $e; } } $item = $e->parent(); } $breadcrumb = array_reverse($route); printout($breadcrumb, $bottom_content, $n); $n = $n + 1; } } } ?>
ブラウザ上の見た目として、左→右とたどれば、「左の1」、「右の1」、一段下に降りて、「左の2」、「右の2」とたどることになりますが、HTML 上は「左の1」、「左の2」と続いているので、それの順番で出力されます。
Phpfiddle で試した結果です。
http://phpfiddle.org/lite/code/02jk-wduu