我已经在php
中编写了一些代码,以从Wikipedia主页上刮下一些首选的链接。当我执行脚本时,链接也会相应地通过。
但是,在这一点上,我已经在脚本中定义了两个函数,以便学习如何将链接从一个函数传递到另一个函数。现在,我的目标是在后一个功能中打印链接,但只打印第一个链接,而没有其他内容。
如果仅使用此功能fetch_wiki_links()
,则可以获得多个链接,但是当我尝试在get_links_in_ano_func()
中打印相同的链接时,它将仅打印第一个链接。
即使使用第二个功能,也如何获得所有这些信息?
这是我到目前为止写的:
include("simple_html_dom.php");
$prefix = "https://en.wikipedia.org";
function fetch_wiki_links($prefix)
{
$weblink = "https://en.wikipedia.org/wiki/Main_Page";
$htmldoc = file_get_html($weblink);
foreach ($htmldoc->find("a[href^='/wiki/']") as $a) {
$links = $a->href . '<br>';
$absolute_links = $prefix . $links;
return $absolute_links;
}
}
function get_links_in_ano_func($absolute_links)
{
echo $absolute_links;
}
$items = fetch_wiki_links($prefix);
get_links_in_ano_func($items);
答案 0 :(得分:3)
您的函数在第一次迭代时就返回了值。您将需要以下内容:
function fetch_wiki_links($prefix)
{
$weblink = "https://en.wikipedia.org/wiki/Main_Page";
$htmldoc = file_get_html($weblink);
$absolute_links = array();
foreach ($htmldoc->find("a[href^='/wiki/']") as $a) {
$links = $a->href . '<br>';
$absolute_links []= $prefix . $links;
}
return implode("\n", $absolute_links);
}