【问题标题】:Simple PHP web-scraping script gone wrong简单的 PHP 网页抓取脚本出错了
【发布时间】:2011-12-24 17:46:19
【问题描述】:

我对编程非常陌生,并且已经将我的头撞到墙上试图制作这个网络抓取工具 2 天了。我简化了完整的脚本(甚至删除了所有实际的网络抓取),同时保持了原来的功能障碍。

我想代码对于受过训练的眼睛来说很容易理解,但为了方便起见,我会说脚本应该:

  1. 用子数组填充数组
  2. 为每个子数组设置一些值,但将最后一个子数组值留空
  3. a) 使用另一个函数 3.b) 获取最后一个子数组值,然后将它们插入到原始数组中

3.b 是脚本失败的地方。不输入值(留空)。

我知道我正在使用没有参数的函数(完整的代码包括它们),这可能很糟糕,但没有它们,功能障碍仍然存在。

<?php
    $scrape = new Scraper();

    class Scraper
    {
        protected $cars = array();

        function __construct()
        {
            $this->getcars();

            foreach ($this->cars as $item) {
                $item['color'] = $this->getcolor($item); // here is the fault!
            }
        }

        private function getcars()
        {
            $listofcars = array('0','1','2');
            foreach ($listofcars as $item) {
                $this->cars[] = array('carname' => 'humvee','color' => '');
            }
        }

        private function getcolor()
        {
            return 'green';
        }
    }
?>

【问题讨论】:

  • $this->getcolor() WITH参数的定义在哪里?
  • 这个问题我恐怕不明白。不过,我将提供整个代码的链接:link 根据 GigaWatt 或 Grok 建议的更改,它终于可以工作了 - 非常感谢!
  • 在 GigaWatt 答案的编辑中有解释。

标签: php class function constructor web-scraping


【解决方案1】:

通过引用的解决方案有效,但你也可以试试这个:

<?php
    function __construct() {
        $this->cars = $this->getcars();
        foreach ($this->cars as $item) {
            $item['color'] = $this->getcolor($item);
        }
    }

    private function getcars() {
        $data = array();
        $listofcars = array('0','1','2');
        foreach ($listofcars as $item) {
            $data[] = array('carname' => 'humvee','color' => '');
        }
        return $data;
    }

    private function getcolor() {
        return 'green';
    }
?>

【讨论】:

    【解决方案2】:

    您的 foreach 循环没有通过引用传递(您所做的任何更改都不会“坚持”)。将其更改为:

    foreach ($this-&gt;cars as &amp;$item)

    编辑: 看起来$this-&gt;getcolor($item); 也可能是个问题。您定义的 getcolor() 函数不带参数,因此您可能希望将其设为 $this-&gt;getcolor();

    【讨论】:

      猜你喜欢
      • 2021-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      • 1970-01-01
      • 2023-03-22
      相关资源
      最近更新 更多