在foreach循环中声明函数

时间:2017-03-10 17:27:21

标签: php dom

我正在尝试创建一个foreach循环,它将访问一系列链接中的链接,并从每个访问过的网站获取内容。

但是当我尝试运行它时:

<?php
    require('simple_html_dom.php');

    // Create DOM from URL or file
    $html = file_get_html('http://www.forgolf.cz/index.php/novinky.html');

   $titles = [];
    $links = [];
    $img_src = [];
    $paragraph = [];

   foreach ($html->find('h2 a') as $title) {

       $links[] = $title->getAttribute('href');
        $titles[] = $title->innertext;
    }

   foreach ($html->find('.item-inner p img') as $img) {
        $img_src[] = $img->getAttribute('src');
    }


   foreach ($links as $link) {
        require('simple_html_dom.php');

        $html = file_get_html('http://www.forgolf.cz'. $link);
        foreach ($html-find('.item-page p') as $p) {
            if (is_string($p))
                $paragraph[] = $p->innertext;
        }
    }
?>

我得到Fatal error: Cannot redeclare file_get_html()

当我不包括require('simple_html_dom.php');

我得到:Fatal error: Uncaught Error: Call to undefined function find()

所以我真的很困惑。

任何人都有任何想法如何修复它。

2 个答案:

答案 0 :(得分:0)

更改

require('simple_html_dom.php');

require_once('simple_html_dom.php');

在所有调用此函数的实例中,不仅仅是在内循环中。

答案 1 :(得分:0)

请更改代码几行

undefined

最后代码

 foreach ($links as $link) {
        require('simple_html_dom.php'); **// here** comment line like **//require('simple_html_dom.php');**

        $html = file_get_html('http://www.forgolf.cz'. $link);
        foreach ($html-find('.item-page p') as $p) {
            if (is_string($p))
                $paragraph[] = $p->innertext;
        }
    }
?>