【问题标题】:How to remove unwanted characters from Guzzlehttp json reposnce如何从 Guzzlehttp json 响应中删除不需要的字符
【发布时间】:2015-11-05 16:01:04
【问题描述】:

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

$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-&gt;getBody(substr($res, 3, strlen($res));没有任何运气我无法在 guzzle 文档页面上找到此问题的任何答案,除非说任何自定义 json_decode 选项应该在 getBody() 选项中执行。

【问题讨论】:

    标签: php json laravel laravel-4 guzzle


    【解决方案1】:

    我最近在 github 上发现了 Colin Viebrock 的这段代码,

    $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 中发挥作用,希望这可以帮助任何人如何使用 Guzzle 获得“无法将响应正文解析为 JSON:4”。

    【讨论】:

      【解决方案2】:

      你需要做的

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

      而不是

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

      【讨论】:

      • 嗨 jedrzej.kurylo 有没有关于可以在 guzzlehttp 中使用的参数的文档?
      • 我不知道。肯定有 guzzlehttp github 上的文档。但是这个修复与 guzzle 无关,它只是对字符串的操作
      猜你喜欢
      • 2013-04-17
      • 1970-01-01
      • 2022-01-12
      • 2021-11-16
      • 2014-09-05
      • 2021-06-27
      • 2017-06-04
      • 2018-12-22
      相关资源
      最近更新 更多