我正在做一个剪贴练习,它可以工作,但是我想不出一种以所需格式输出数据的方法:
quote quote quote quote quote : author
quote quote quote quote quote : author
quote quote quote quote quote : author
我只能得到:
quote quote quote quote quote
quote quote quote quote quote
quote quote quote quote quote
author
author
author
码:
$html = file_get_contents('http://www.brainyquote.com/authors/buddha');
$dom = new DOMDocument;
@$dom->loadHTML($html);
$classname1="b-qt";
$classname2="bq-aut";
$finder = new DomXPath($dom);
$quotes = $finder->query("//*[contains(@class, '$classname1')]//text()");
$authors = $finder->query("//*[contains(@class, '$classname2')]//text()");
foreach ($quotes as $quote){
echo $quote->textContent . '<br>';
}
foreach ($authors as $author){
echo $author->textContent . '<br>';
}
最佳答案
根据当前输出,您会发现两个数组具有相同数量的元素
因此,您可以:-
foreach ($quotes as $key=> $quote){
echo $quote->textContent .' : '.$authors[$key]->textContent;
}
如果元素数量不同,则:-
$quote_count = count($quotes);
$author_count = count($authors);
if($quote_count > $author_count ){
foreach ($quotes as $key =>$quote){
echo $quote->textContent .' : '. $authors[$key]->textContent;
}
}else {
foreach ($authors as $key =>$author){
echo $quote[$key]->textContent .' : '. $author->textContent;
}
}
关于php - 使用PHP XPatch在同一foreach循环中从多个域回显文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49587278/