4

私は Web サイトのクロールに取り組んでおり、これまでのところ Goutte で HTML を解析するのに問題はありません。しかし、Web サイトから 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

ありがとうございました。

4

4 に答える 4

16

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

(Goutte + Guzzle) を介した Cookie を使用した JSON の解析-認証用

サイトのページの 1 つ (メイン ページの方が見栄えが良い) に要求を送信して 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

お役に立てば幸いです。なぜなら、Gouttle とそのコンポーネントを理解するのにほぼ 3 日を費やしているからです。

于 2013-09-11T12:52:41.547 に答える
2

数時間の検索の後にこれを理解しました。これを行うだけです:

$client = new Client(); // Goutte Client
$crawler = $client->request("GET", "http://foo.bar");

$jsonData = $crawler->text();
于 2015-03-31T00:52:32.867 に答える
1

mithaaydogmus のソリューションは私にとってはうまくいきませんでした。新しいクラス「BetterClient」を作成しました。

use Goutte\Client as GoutteClient;

class BetterClient extends GoutteClient
{
    private $guzzleResponse;

    public function getGuzzleResponse() {
        return $this->guzzleResponse;
    }

    protected function createResponse($response)
    {
        $this->guzzleResponse = $response;
        return parent::createResponse($response);
    }
}

使用法:

$client = new BetterClient();
$request = $client->request('GET', $url);
$data = $client->getGuzzleResponse()->json();
于 2014-09-19T20:52:46.610 に答える
1

次の方法で JSON を取得することもできます。

$client->getResponse()->getContent()->getContents()
于 2016-05-09T21:54:50.677 に答える