Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
162 views
Welcome To Ask or Share your Answers For Others

1 Answer

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("
", $absolute_links);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...