【发布时间】: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