问题描述
我已经在 php
中编写了一些代码来从维基百科的主页中抓取一些更可取的链接.当我执行我的脚本时,链接会相应地通过.
I've written some code in php
to scrape some preferable links out of the main page of wikipedia. When I execute my script, the links are coming through accordingly.
然而,此时我已经在我的脚本中定义了两个函数,以了解如何将链接从一个函数传递到另一个函数.现在,我的目标是打印后一个函数中的链接,但它只打印第一个链接,不打印其他任何内容.
However, at this point I've defined two functions within my script in order to learn how to pass links from one function to another. Now, my goal is to print the links in the latter function but it only prints the first link and nothing else.
如果我只使用这个函数 fetch_wiki_links()
,我可以获得多个链接,但是当我尝试在 get_links_in_ano_func()
中打印相同的链接时,它会打印第一个链接只要.
If I use only this function fetch_wiki_links()
, I can get several links but when i try to print the same within get_links_in_ano_func()
then it prints the first link only.
即使我使用第二个功能,我如何才能获得它们?
How can I get them all even when I use the second function?
这是我目前所写的:
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);
推荐答案
您的函数在第一次迭代时返回值.你将需要这样的东西:
Your function returned the value at the very first iteration. You will need something like this:
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);
}
这篇关于无法在另一个函数中打印链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!