简体   繁体   中英

Get multiple elements with DOMDocument

i need to parse html like :

<div class="item"><div class="title">title 1</div><div class="date">day 1</div></div>
<div class="item"><div class="title">title 2</div><div class="date">day 2</div></div>
<div class="item"><div class="title">title 3</div><div class="date">day 3</div></div>

Actually i do something like this :

$title = $xpath->query('//div[@class="title"]//text()');
foreach ($title as $title)
{
  $title = trim($title->nodeValue);
}

$date = $xpath->query('//div[@class="date"]//text()');
foreach ($date as $date)
{
  $date = trim($date->nodeValue);
}

But with this i take only one item, so i looking for the proper way to get all the items in the same while.

You probably want to loop over the item elements, then find their respective title and date text.

$items = $xpath->query('//div[@class="item"]');
foreach ($items as $item) {
    $title = $xpath->evaluate('string(div[@class="title"])', $item);
    $date  = $xpath->evaluate('string(div[@class="date"])', $item);
    echo "$title $date\n";
}

» See the above example running online .

I don't really understand your problem. The loops work as expected and you can just accumulate all titles and dates in an array for example. Although I wouldn't reuse the same variable names again.

$titles = $xpath->query('//div[@class="title"]//text()');
foreach ($titles as $title)
{
    $all_titles[] = trim($title->nodeValue);
}

$dates = $xpath->query('//div[@class="date"]//text()');
foreach ($dates as $date)
{
    $all_dates[] = trim($date->nodeValue);
}

codepad for testing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM