我有这些标签:
<div class="entry">entry #1</div>
<div class="subtitle">subtitle</div>
<div class="body">blah blah blah</div>
<div class="entry">entry #2</div>
<div class="subtitle">subtitle</div>
<div class="body">blah blah blah</div>
<div class="entry">entry #3</div>
<div class="subtitle">subtitle</div>
<div class="body">blah blah blah</div>
<div class="entry">entry #4</div>
<div class="subtitle">subtitle</div>
<div class="body">blah blah blah</div>
等等。如何在PHP中的每个“入口”类之间获取每个内容?使用simple_html_dom_parse还是XPath?
答案 0 :(得分:0)
猜测这就是你想要的:
<?php
// set up to parse our input
$dom = new DOMDocument();
$dom->loadHTMLFile("./input.html");
$xpath = new DOMXPath($dom);
// initialize array to put items in and initialize an item
$list = array();
$item = array();
$divs = $xpath->query("//div");
echo "len: {$divs->length}\n";
foreach ($divs as $div) {
$class = $div->getAttribute("class");
// each time we see an entry, add the item we've collected
if ($class == "entry") {
if (count($item) > 0) $list[] = $item;
$item = array();
}
// otherwise add to the item we're working on
else {
$item[$class] = $div->childNodes->item(0)->nodeValue;
}
}
// pick up the last item we were working on
$list[] = $item;
// and print the result
var_dump($list);
?>