可以用Goutte解析JSON吗?

mit*_*mus 4 php json html-parsing goutte

我正在抓取网站,到目前为止,使用Goutte解析HTML没有问题.但我需要从网站检索JSON,并且由于cookie管理,我不想这样做file_get_contents()- 这不起作用.

我可以使用纯cURL但在这种情况下我只想使用Goutte而不想使用任何其他库.

那么有什么方法可以通过Goutte解析文本,或者我真的必须用好的旧方法来做这个吗?

/* Sample Code */
$client = new Client();
$crawler = $client->request('foo');
$crawler = $crawler->filter('bar'); // of course not working
Run Code Online (Sandbox Code Playgroud)

谢谢.

mit*_*mus 14

在Goutte图书馆深入搜索后,我发现了一种方式,我想分享.因为Goutte是非常强大的库,但是文档非常复杂.

通过(Goutte> Guzzle)解析JSON

只需获取所需的输出页面并将json存储到数组中.

$client = new Client(); // Goutte Client
$request = $client->getClient()->createRequest('GET', 'http://***.json');   
/* getClient() for taking Guzzle Client */

$response = $request->send(); // Send created request to server
$data = $response->json(); // Returns PHP Array
Run Code Online (Sandbox Code Playgroud)

通过(Goutte + Guzzle)解析带有Cookie的JSON - 用于身份验证

发送请求之一的网站页面(主页看起来更好)获取cookie,然后使用这些cookie进行身份验证.

$client = new Client(); // Goutte Client
$crawler = $client->request("GET", "http://foo.bar");
/* Send request directly and get whole data. It includes cookies from server and 
it automatically stored in Goutte Client object */

$request = $client->getClient()->createRequest('GET', 'http://foo.bar/baz.json');
/* getClient() for taking Guzzle Client */

$cookies = $client->getRequest()->getCookies();
foreach ($cookies as $key => $value) {
   $request->addCookie($key, $value);
}

/* Get cookies from Goutte Client and add to cookies in Guzzle request */

$response = $request->send(); // Send created request to server
$data = $response->json(); // Returns PHP Array
Run Code Online (Sandbox Code Playgroud)

我希望它有所帮助.因为我几乎花了3天时间来了解Gouttle及其组件.