如何从Guzzlehttp json reposnce中删除不需要的字符

时间:2015-08-12 21:09:40

标签: php json laravel laravel-4 guzzle

您好我是Laravel的新手,并且已经在Guzzelhttp的Goutte上尝试了几个turtorials但是我仍然无法弄清楚如何使用curl和json_decode从json响应的开头删除3个不需要的charactures。

$url = "URL to atom feed";
$user = "user";
$pass = "pass";

// using CURL to get our results
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, $user . ":" . $pass);
$output = curl_exec($ch);
curl_close($ch);

// decoding our results into an associative array
// doing a substring as there are 3 weird characters being passed back from IIS in front of the string
$data = json_decode(substr($output, 3, strlen($output)), true);

// grabbing our results object
$list = $data['$resources'];

我在ScrapeController中,

<?php

// app/controllers/ScrapeController.php
class ScrapeController extends BaseController {

    public function getIndex() {
        echo "Scrape index page.";
    }

    public function getNode($node) {
        echo "Scraped page $node";
    }

    public function getPages() {
        $client = new GuzzleHttp\Client();
        $res = $client->get('URL to atom feed', ['auth' =>  ['user', 'pass']]);
        echo $res->getStatusCode();
        // "200"
       // echo $res->getHeader('content-type');
        // 'application/json; charset=utf8'
       echo $res->getBody();
        // {"type":"User"...'

这是我尝试过的$res->getBody(substr($res, 3, strlen($res));没有任何运气我无法在guzzle文档页面找到任何问题的答案,除了说任何自定义json_decode选项应该在getBody()选项中执行。

2 个答案:

答案 0 :(得分:1)

你需要做

$body = substr($res->getBody(), 3)

而不是

$body = $res->getBody(substr($res, 3, strlen($res))

答案 1 :(得分:0)

我最近在Colin Viebrock的github上找到了这段代码,

$client = new Guzzle\Http\Client('http://example.com');

$client->addSubscriber( new Cviebrock\Guzzle\Plugin\StripBom\StripBomPlugin() );

$request = $client->get('some/request');

$response = $client->send($request);

$data = $response->json();

在laravel中工作希望这可以帮助任何人如何获取&#34;无法将响应体解析为JSON:4&#34;使用Guzzle。