doupo5178 2017-03-10 17:27
浏览 59
已采纳

在foreach循环中声明函数

I am trying to create a foreach loop which would visit a link from an array of links and get contents from each of the visited websites.

But when I try to run it:

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

I get Fatal error: Cannot redeclare file_get_html()

And when I dont include the require('simple_html_dom.php');

I get: Fatal error: Uncaught Error: Call to undefined function find()

So I am realy confused.

Anyone got any ideas how to repaire this.

  • 写回答

2条回答 默认 最新

  • duanfengdian7014 2017-03-10 17:42
    关注

    please change code few line

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

    Finally Code

        <?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;
            }
        }
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里