【问题标题】:PHP return array when scraping with Goutte使用 Goutte 抓取时 PHP 返回数组
【发布时间】:2015-07-07 12:57:12
【问题描述】:

我正在尝试使用 goutte 返回一组项目,我可以将它们打印出来,但我希望它们在一个数组中,就像一个 API。这是示例代码。我正在使用 Laravel 5.1。

public function index()
{
    $posts = array();
    $client = new Client();
    $crawler = $client->request('GET', 'http://www.icetimux.com');

    $crawler->filter('h2 > a')->each(function ($node) use ($posts){
        // print $node->text(); //this prints them, needs to return as an array :(
        array_push($posts, $node->text());
    });
    return $posts;
}

我得到的只是一个空数组。

【问题讨论】:

  • 对我来说看起来不错。虽然你可以使用 $posts[] = $node->text();而不是 array_push(...)。你确定这个函数返回了一个空数组吗?也许 $node->text() 不是一个真正的字符串,你可以试试 $posts[] = ''.$node->text();以确保值被复制并且这些副本保持存在。
  • 试过array_push($posts, (string)$node->text()); 仍然是一个空数组。还尝试了$posts[] = ''.$node->text(); 并且也是空的。我在浏览器中看到这个[ ](我使用 JSON 视图 chrome 扩展)
  • 您在将数组发送到客户端之前使用了 json_encode()?
  • @RhinoDevel 是的,还是空的。 return json_encode($posts)
  • 这个函数是否应该直接将数据发送给客户端?那您不需要使用 print 而不是 return 吗?!

标签: php api goutte laravel-5.1


【解决方案1】:

哈哈!我做的!看看吧!

public function index()
{
    $client = new Client();
    $crawler = $client->request('GET', 'http://www.icetimux.com');

    return $result = $crawler->filter('h2 > a')->each(function ($node){
        return $posts[] = $node->text();
    });
}

【讨论】:

  • 我期望使用您在问题中显示的相同方法获得相同的结果。我试过但没有用。我碰巧用你的解决方案运行它。谢谢!
猜你喜欢
  • 2018-10-23
  • 2018-10-17
  • 2014-09-22
  • 1970-01-01
  • 2021-04-18
  • 2020-10-10
  • 2015-05-18
  • 2022-11-23
  • 1970-01-01
相关资源
最近更新 更多