Unable to print links in another function

2019-09-21 15:13发布

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.

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?

This is what I've written so far:

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);

1条回答
我命由我不由天
2楼-- · 2019-09-21 15:58

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);
}
查看更多
登录 后发表回答