我不知道我做错了什么。 每次它通过时,它都会不断循环并拉出同一行中列出的所有城市并将它们与州放在一起,然后当它进入下一个州时,它会从正确的位置开始,但仍然继续前进。 我已经尝试了 4 个小时,只是想不通。
$url = 'http://www.craigslist.org/about/sites';
$output = file_get_contents($url);
$doc = new DOMDocument();
libxml_use_internal_errors(true); //Supress Warnings for HTML5 conversion issue
$doc->loadHTML($output);
libxml_use_internal_errors(false); //Start Showing Errors
$xpath = new DOMXpath($doc);
foreach ($xpath->query('//h1') as $e) {
$country = $e->nodeValue;
$list = array();
foreach ($xpath->query('./following-sibling::div[@class="colmask"]', $e) as $li) {
foreach ($xpath->query('//div/h4', $e) as $div) {
$state = $div->nodeValue;
foreach ($xpath->query('./following-sibling::ul/li', $div) as $div2) {
$href = $div2->getAttribute("href");
$text = trim(preg_replace("/['r'n]+/", " ", $div2->nodeValue));
echo 'Country: ' . $country . ' State: ' . $state . ' CITY: text['. $text . '] href[' . $href . '] <br/><br/><br/>';
}
}
}
}
在执行此操作时应避免嵌套query
调用。而是使用在每次迭代中获得的 DOMNodeList,以及 item
方法。
例如,而不是写:
foreach ($xpath->query('./following-sibling::div[@class="colmask"]', $e) as $li) {
foreach ($xpath->query('//div/h4', $e) as $div) {
$state = $div->nodeValue;
写:
$result = $xpath->query('./following-sibling::div[@class="colmask"]', $e);
$state = $result->item(0)->nodeValue;
如果需要从 DOMNode $state
导航,请使用 $state->parentNode
、 $state->nextSibling
和/或 $state->previousSibling
有一个叫达菲达克的人回答了我的问题。 这是答案..
foreach ($xpath->query('./following-sibling::ul[1]/li', $div) as $div2) {
$href = $div2->getAttribute("href");
$text = trim(preg_replace("/['r'n]+/", " ", $div2->nodeValue));
echo 'Country: ' . $country . ' State: ' . $state . ' CITY: text['. $text . '] href[' . $href . '] <br/><br/><br/>';
}
缺少的部分是 [1] 引用找到的第一个 UL,而不是任何超出该 UL 的内容