Unable to print links in another function

我与影子孤独终老i 提交于 2019-12-13 08:06:28

问题


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:


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


来源:https://stackoverflow.com/questions/52346719/unable-to-print-links-in-another-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!