Get only the first result of a foreach loop
I am trying to display all the links that are located in <div class="post">
. There are many <div class="post">
inside my page (it is a blog). However there are many links in every <div class="post">
but I want to display the first of every div.
My question is how ca开发者_运维百科n I limit my code to show only the first one and continue to the next div?
Below is my code that gets and displays all the links. Gracias!
<?php
$dom = new DOMDocument;
libxml_use_internal_errors(TRUE);
$dom->loadHTMLFile('http://www.mydomain.com/');
libxml_clear_errors();
$xPath = new DOMXPath($dom);
$links = $xPath->query('//div[@class="post"]/a/@href');
foreach($links as $link) {
printf("%s \n", $link->nodeValue);
}
?>
:)
$xPath = new DOMXPath($dom);
$links = $xPath->query('//div[@class="post"]/a/@href');
$i = 1;
foreach($links as $link) {
printf("%s \n", $link->nodeValue);
if($i == 1) break;
}
I want to display the first [link] of every div.
The following asks for the href
s from only the first link (at any depth) within each of the divs
//div[@class="post"]/descendant::a[1]/@href
If you want to only accept links which are immediate children of the div, then remove descendant::
from the above.
So, similarly to your existing code, the PHP might look something like
$links = $xPath->query('//div[@class="post"]/descendant::a[1]/@href');
foreach($links as $link) {
printf("%s \n", $link->value);
}
You are now searchig for each link inside a div, so the data in $links contains no information at all about in what div the link occured. To find the first link in each div you will first have to query (somehow) for all divs. Then foreach div find all links in the div and select the first (or immediatly select the first link in that div if possible.
You can probably get an array of divs via the dom object or via xPath.
精彩评论