Guzzle 6: no more json() method for responses












133















Previously in Guzzle 5.3:



$response = $client->get('http://httpbin.org/get');
$array = $response->json(); // Yoohoo
var_dump($array[0]['origin']);


I could easily get a PHP array from a JSON response. Now In Guzzle 6, I don't know how to do. There seems to be no json() method anymore. I (quickly) read the doc from the latest version and don't found anything about JSON responses. I think I missed something, maybe there is a new concept that I don't understand (or maybe I did not read correctly).



Is this (below) new way the only way?



$response = $client->get('http://httpbin.org/get');
$array = json_decode($response->getBody()->getContents(), true); // :'(
var_dump($array[0]['origin']);


Or is there an helper or something like that?










share|improve this question





























    133















    Previously in Guzzle 5.3:



    $response = $client->get('http://httpbin.org/get');
    $array = $response->json(); // Yoohoo
    var_dump($array[0]['origin']);


    I could easily get a PHP array from a JSON response. Now In Guzzle 6, I don't know how to do. There seems to be no json() method anymore. I (quickly) read the doc from the latest version and don't found anything about JSON responses. I think I missed something, maybe there is a new concept that I don't understand (or maybe I did not read correctly).



    Is this (below) new way the only way?



    $response = $client->get('http://httpbin.org/get');
    $array = json_decode($response->getBody()->getContents(), true); // :'(
    var_dump($array[0]['origin']);


    Or is there an helper or something like that?










    share|improve this question



























      133












      133








      133


      15






      Previously in Guzzle 5.3:



      $response = $client->get('http://httpbin.org/get');
      $array = $response->json(); // Yoohoo
      var_dump($array[0]['origin']);


      I could easily get a PHP array from a JSON response. Now In Guzzle 6, I don't know how to do. There seems to be no json() method anymore. I (quickly) read the doc from the latest version and don't found anything about JSON responses. I think I missed something, maybe there is a new concept that I don't understand (or maybe I did not read correctly).



      Is this (below) new way the only way?



      $response = $client->get('http://httpbin.org/get');
      $array = json_decode($response->getBody()->getContents(), true); // :'(
      var_dump($array[0]['origin']);


      Or is there an helper or something like that?










      share|improve this question
















      Previously in Guzzle 5.3:



      $response = $client->get('http://httpbin.org/get');
      $array = $response->json(); // Yoohoo
      var_dump($array[0]['origin']);


      I could easily get a PHP array from a JSON response. Now In Guzzle 6, I don't know how to do. There seems to be no json() method anymore. I (quickly) read the doc from the latest version and don't found anything about JSON responses. I think I missed something, maybe there is a new concept that I don't understand (or maybe I did not read correctly).



      Is this (below) new way the only way?



      $response = $client->get('http://httpbin.org/get');
      $array = json_decode($response->getBody()->getContents(), true); // :'(
      var_dump($array[0]['origin']);


      Or is there an helper or something like that?







      php guzzle






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jun 1 '15 at 9:56







      rap-2-h

















      asked May 29 '15 at 12:53









      rap-2-hrap-2-h

      9,695769129




      9,695769129
























          5 Answers
          5






          active

          oldest

          votes


















          225














          I use json_decode($response->getBody()) now instead of $response->json().



          I suspect this might be a casualty of PSR-7 compliance.






          share|improve this answer



















          • 4





            Nothing in the documentation that makes this explicit but it does appear they've phased out the $response->json() helper.

            – paperclip
            Jun 8 '15 at 15:35






          • 11





            Confirmed. Due to PSR-7: github.com/guzzle/guzzle/issues/1106

            – paperclip
            Jun 9 '15 at 11:42






          • 46





            If you're expecting an array response like how the original ->json() worked, use json_decode($response->getBody(), true) instead to get an array instead of a stdObject

            – Jay El-Kaake
            Dec 23 '15 at 4:53








          • 3





            Using strict_types, I needed to cast the Guzzle response body to string before decoding it: json_decode((string) $response->getBody(), true)

            – Yoan Tournade
            Mar 23 '18 at 12:15



















          90














          You switch to:



          json_decode($response->getBody(), true)


          Instead of the other comment if you want it to work exactly as before in order to get arrays instead of objects.






          share|improve this answer































            13














            I use $response->getBody()->getContents() to get JSON from response.
            Guzzle version 6.3.0.






            share|improve this answer
























            • Yeah! not sure why this has no other upvotes. :-)

              – BizzyBob
              May 31 '18 at 3:34











            • Other options don't work for me. This one does.

              – Strabek
              Jun 18 '18 at 10:39











            • Calling getContents() in the response body will empty the stream and the next call to getContents() will return empty. If you want to get the body as string use: strval($response->getBody())

              – JVitela
              Aug 1 '18 at 15:47





















            0














            Adding ->getContents() doesn't return jSON response, instead it returns as text.



            You can simply use json_decode






            share|improve this answer


























            • It returns JSON as text, not HTML.

              – František Maša
              Jul 13 '18 at 6:23











            • You are right, thank you, I've edited my reply.

              – Moh
              Jul 14 '18 at 6:54



















            0














            If you guys still interested, here is my workaround based on Guzzle middleware feature:





            1. Create JsonAwaraResponse that will decode JSON response by Content-Type HTTP header, if not - it will act as standard Guzzle Response:



              <?php

              namespace GuzzleHttpPsr7;


              class JsonAwareResponse extends Response
              {
              /**
              * Cache for performance
              * @var array
              */
              private $json;

              public function getBody()
              {
              if ($this->json) {
              return $this->json;
              }
              // get parent Body stream
              $body = parent::getBody();

              // if JSON HTTP header detected - then decode
              if (false !== strpos($this->getHeaderLine('Content-Type'), 'application/json')) {
              return $this->json = json_decode($body, true);
              }
              return $body;
              }
              }



            2. Create Middleware which going to replace Guzzle PSR-7 responses with above Response implementation:



              <?php

              $client = new GuzzleHttpClient();

              /** @var HandlerStack $handler */
              $handler = $client->getConfig('handler');
              $handler->push(GuzzleHttpMiddleware::mapResponse(function (PsrHttpMessageResponseInterface $response) {
              return new GuzzleHttpPsr7JsonAwareResponse(
              $response->getStatusCode(),
              $response->getHeaders(),
              $response->getBody(),
              $response->getProtocolVersion(),
              $response->getReasonPhrase()
              );
              }), 'json_decode_middleware');



            After this to retrieve JSON as PHP native array use Guzzle as always:



            $jsonArray = $client->get('http://httpbin.org/headers')->getBody();


            Tested with guzzlehttp/guzzle 6.3.3






            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f30530172%2fguzzle-6-no-more-json-method-for-responses%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              5 Answers
              5






              active

              oldest

              votes








              5 Answers
              5






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              225














              I use json_decode($response->getBody()) now instead of $response->json().



              I suspect this might be a casualty of PSR-7 compliance.






              share|improve this answer



















              • 4





                Nothing in the documentation that makes this explicit but it does appear they've phased out the $response->json() helper.

                – paperclip
                Jun 8 '15 at 15:35






              • 11





                Confirmed. Due to PSR-7: github.com/guzzle/guzzle/issues/1106

                – paperclip
                Jun 9 '15 at 11:42






              • 46





                If you're expecting an array response like how the original ->json() worked, use json_decode($response->getBody(), true) instead to get an array instead of a stdObject

                – Jay El-Kaake
                Dec 23 '15 at 4:53








              • 3





                Using strict_types, I needed to cast the Guzzle response body to string before decoding it: json_decode((string) $response->getBody(), true)

                – Yoan Tournade
                Mar 23 '18 at 12:15
















              225














              I use json_decode($response->getBody()) now instead of $response->json().



              I suspect this might be a casualty of PSR-7 compliance.






              share|improve this answer



















              • 4





                Nothing in the documentation that makes this explicit but it does appear they've phased out the $response->json() helper.

                – paperclip
                Jun 8 '15 at 15:35






              • 11





                Confirmed. Due to PSR-7: github.com/guzzle/guzzle/issues/1106

                – paperclip
                Jun 9 '15 at 11:42






              • 46





                If you're expecting an array response like how the original ->json() worked, use json_decode($response->getBody(), true) instead to get an array instead of a stdObject

                – Jay El-Kaake
                Dec 23 '15 at 4:53








              • 3





                Using strict_types, I needed to cast the Guzzle response body to string before decoding it: json_decode((string) $response->getBody(), true)

                – Yoan Tournade
                Mar 23 '18 at 12:15














              225












              225








              225







              I use json_decode($response->getBody()) now instead of $response->json().



              I suspect this might be a casualty of PSR-7 compliance.






              share|improve this answer













              I use json_decode($response->getBody()) now instead of $response->json().



              I suspect this might be a casualty of PSR-7 compliance.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered May 29 '15 at 18:33









              meriialmeriial

              2,72111618




              2,72111618








              • 4





                Nothing in the documentation that makes this explicit but it does appear they've phased out the $response->json() helper.

                – paperclip
                Jun 8 '15 at 15:35






              • 11





                Confirmed. Due to PSR-7: github.com/guzzle/guzzle/issues/1106

                – paperclip
                Jun 9 '15 at 11:42






              • 46





                If you're expecting an array response like how the original ->json() worked, use json_decode($response->getBody(), true) instead to get an array instead of a stdObject

                – Jay El-Kaake
                Dec 23 '15 at 4:53








              • 3





                Using strict_types, I needed to cast the Guzzle response body to string before decoding it: json_decode((string) $response->getBody(), true)

                – Yoan Tournade
                Mar 23 '18 at 12:15














              • 4





                Nothing in the documentation that makes this explicit but it does appear they've phased out the $response->json() helper.

                – paperclip
                Jun 8 '15 at 15:35






              • 11





                Confirmed. Due to PSR-7: github.com/guzzle/guzzle/issues/1106

                – paperclip
                Jun 9 '15 at 11:42






              • 46





                If you're expecting an array response like how the original ->json() worked, use json_decode($response->getBody(), true) instead to get an array instead of a stdObject

                – Jay El-Kaake
                Dec 23 '15 at 4:53








              • 3





                Using strict_types, I needed to cast the Guzzle response body to string before decoding it: json_decode((string) $response->getBody(), true)

                – Yoan Tournade
                Mar 23 '18 at 12:15








              4




              4





              Nothing in the documentation that makes this explicit but it does appear they've phased out the $response->json() helper.

              – paperclip
              Jun 8 '15 at 15:35





              Nothing in the documentation that makes this explicit but it does appear they've phased out the $response->json() helper.

              – paperclip
              Jun 8 '15 at 15:35




              11




              11





              Confirmed. Due to PSR-7: github.com/guzzle/guzzle/issues/1106

              – paperclip
              Jun 9 '15 at 11:42





              Confirmed. Due to PSR-7: github.com/guzzle/guzzle/issues/1106

              – paperclip
              Jun 9 '15 at 11:42




              46




              46





              If you're expecting an array response like how the original ->json() worked, use json_decode($response->getBody(), true) instead to get an array instead of a stdObject

              – Jay El-Kaake
              Dec 23 '15 at 4:53







              If you're expecting an array response like how the original ->json() worked, use json_decode($response->getBody(), true) instead to get an array instead of a stdObject

              – Jay El-Kaake
              Dec 23 '15 at 4:53






              3




              3





              Using strict_types, I needed to cast the Guzzle response body to string before decoding it: json_decode((string) $response->getBody(), true)

              – Yoan Tournade
              Mar 23 '18 at 12:15





              Using strict_types, I needed to cast the Guzzle response body to string before decoding it: json_decode((string) $response->getBody(), true)

              – Yoan Tournade
              Mar 23 '18 at 12:15













              90














              You switch to:



              json_decode($response->getBody(), true)


              Instead of the other comment if you want it to work exactly as before in order to get arrays instead of objects.






              share|improve this answer




























                90














                You switch to:



                json_decode($response->getBody(), true)


                Instead of the other comment if you want it to work exactly as before in order to get arrays instead of objects.






                share|improve this answer


























                  90












                  90








                  90







                  You switch to:



                  json_decode($response->getBody(), true)


                  Instead of the other comment if you want it to work exactly as before in order to get arrays instead of objects.






                  share|improve this answer













                  You switch to:



                  json_decode($response->getBody(), true)


                  Instead of the other comment if you want it to work exactly as before in order to get arrays instead of objects.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 10 '15 at 21:32









                  dmyersdmyers

                  1,02486




                  1,02486























                      13














                      I use $response->getBody()->getContents() to get JSON from response.
                      Guzzle version 6.3.0.






                      share|improve this answer
























                      • Yeah! not sure why this has no other upvotes. :-)

                        – BizzyBob
                        May 31 '18 at 3:34











                      • Other options don't work for me. This one does.

                        – Strabek
                        Jun 18 '18 at 10:39











                      • Calling getContents() in the response body will empty the stream and the next call to getContents() will return empty. If you want to get the body as string use: strval($response->getBody())

                        – JVitela
                        Aug 1 '18 at 15:47


















                      13














                      I use $response->getBody()->getContents() to get JSON from response.
                      Guzzle version 6.3.0.






                      share|improve this answer
























                      • Yeah! not sure why this has no other upvotes. :-)

                        – BizzyBob
                        May 31 '18 at 3:34











                      • Other options don't work for me. This one does.

                        – Strabek
                        Jun 18 '18 at 10:39











                      • Calling getContents() in the response body will empty the stream and the next call to getContents() will return empty. If you want to get the body as string use: strval($response->getBody())

                        – JVitela
                        Aug 1 '18 at 15:47
















                      13












                      13








                      13







                      I use $response->getBody()->getContents() to get JSON from response.
                      Guzzle version 6.3.0.






                      share|improve this answer













                      I use $response->getBody()->getContents() to get JSON from response.
                      Guzzle version 6.3.0.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Mar 21 '18 at 11:03









                      jusepjusep

                      13115




                      13115













                      • Yeah! not sure why this has no other upvotes. :-)

                        – BizzyBob
                        May 31 '18 at 3:34











                      • Other options don't work for me. This one does.

                        – Strabek
                        Jun 18 '18 at 10:39











                      • Calling getContents() in the response body will empty the stream and the next call to getContents() will return empty. If you want to get the body as string use: strval($response->getBody())

                        – JVitela
                        Aug 1 '18 at 15:47





















                      • Yeah! not sure why this has no other upvotes. :-)

                        – BizzyBob
                        May 31 '18 at 3:34











                      • Other options don't work for me. This one does.

                        – Strabek
                        Jun 18 '18 at 10:39











                      • Calling getContents() in the response body will empty the stream and the next call to getContents() will return empty. If you want to get the body as string use: strval($response->getBody())

                        – JVitela
                        Aug 1 '18 at 15:47



















                      Yeah! not sure why this has no other upvotes. :-)

                      – BizzyBob
                      May 31 '18 at 3:34





                      Yeah! not sure why this has no other upvotes. :-)

                      – BizzyBob
                      May 31 '18 at 3:34













                      Other options don't work for me. This one does.

                      – Strabek
                      Jun 18 '18 at 10:39





                      Other options don't work for me. This one does.

                      – Strabek
                      Jun 18 '18 at 10:39













                      Calling getContents() in the response body will empty the stream and the next call to getContents() will return empty. If you want to get the body as string use: strval($response->getBody())

                      – JVitela
                      Aug 1 '18 at 15:47







                      Calling getContents() in the response body will empty the stream and the next call to getContents() will return empty. If you want to get the body as string use: strval($response->getBody())

                      – JVitela
                      Aug 1 '18 at 15:47













                      0














                      Adding ->getContents() doesn't return jSON response, instead it returns as text.



                      You can simply use json_decode






                      share|improve this answer


























                      • It returns JSON as text, not HTML.

                        – František Maša
                        Jul 13 '18 at 6:23











                      • You are right, thank you, I've edited my reply.

                        – Moh
                        Jul 14 '18 at 6:54
















                      0














                      Adding ->getContents() doesn't return jSON response, instead it returns as text.



                      You can simply use json_decode






                      share|improve this answer


























                      • It returns JSON as text, not HTML.

                        – František Maša
                        Jul 13 '18 at 6:23











                      • You are right, thank you, I've edited my reply.

                        – Moh
                        Jul 14 '18 at 6:54














                      0












                      0








                      0







                      Adding ->getContents() doesn't return jSON response, instead it returns as text.



                      You can simply use json_decode






                      share|improve this answer















                      Adding ->getContents() doesn't return jSON response, instead it returns as text.



                      You can simply use json_decode







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Jul 14 '18 at 6:54

























                      answered Jun 28 '18 at 9:02









                      MohMoh

                      12




                      12













                      • It returns JSON as text, not HTML.

                        – František Maša
                        Jul 13 '18 at 6:23











                      • You are right, thank you, I've edited my reply.

                        – Moh
                        Jul 14 '18 at 6:54



















                      • It returns JSON as text, not HTML.

                        – František Maša
                        Jul 13 '18 at 6:23











                      • You are right, thank you, I've edited my reply.

                        – Moh
                        Jul 14 '18 at 6:54

















                      It returns JSON as text, not HTML.

                      – František Maša
                      Jul 13 '18 at 6:23





                      It returns JSON as text, not HTML.

                      – František Maša
                      Jul 13 '18 at 6:23













                      You are right, thank you, I've edited my reply.

                      – Moh
                      Jul 14 '18 at 6:54





                      You are right, thank you, I've edited my reply.

                      – Moh
                      Jul 14 '18 at 6:54











                      0














                      If you guys still interested, here is my workaround based on Guzzle middleware feature:





                      1. Create JsonAwaraResponse that will decode JSON response by Content-Type HTTP header, if not - it will act as standard Guzzle Response:



                        <?php

                        namespace GuzzleHttpPsr7;


                        class JsonAwareResponse extends Response
                        {
                        /**
                        * Cache for performance
                        * @var array
                        */
                        private $json;

                        public function getBody()
                        {
                        if ($this->json) {
                        return $this->json;
                        }
                        // get parent Body stream
                        $body = parent::getBody();

                        // if JSON HTTP header detected - then decode
                        if (false !== strpos($this->getHeaderLine('Content-Type'), 'application/json')) {
                        return $this->json = json_decode($body, true);
                        }
                        return $body;
                        }
                        }



                      2. Create Middleware which going to replace Guzzle PSR-7 responses with above Response implementation:



                        <?php

                        $client = new GuzzleHttpClient();

                        /** @var HandlerStack $handler */
                        $handler = $client->getConfig('handler');
                        $handler->push(GuzzleHttpMiddleware::mapResponse(function (PsrHttpMessageResponseInterface $response) {
                        return new GuzzleHttpPsr7JsonAwareResponse(
                        $response->getStatusCode(),
                        $response->getHeaders(),
                        $response->getBody(),
                        $response->getProtocolVersion(),
                        $response->getReasonPhrase()
                        );
                        }), 'json_decode_middleware');



                      After this to retrieve JSON as PHP native array use Guzzle as always:



                      $jsonArray = $client->get('http://httpbin.org/headers')->getBody();


                      Tested with guzzlehttp/guzzle 6.3.3






                      share|improve this answer




























                        0














                        If you guys still interested, here is my workaround based on Guzzle middleware feature:





                        1. Create JsonAwaraResponse that will decode JSON response by Content-Type HTTP header, if not - it will act as standard Guzzle Response:



                          <?php

                          namespace GuzzleHttpPsr7;


                          class JsonAwareResponse extends Response
                          {
                          /**
                          * Cache for performance
                          * @var array
                          */
                          private $json;

                          public function getBody()
                          {
                          if ($this->json) {
                          return $this->json;
                          }
                          // get parent Body stream
                          $body = parent::getBody();

                          // if JSON HTTP header detected - then decode
                          if (false !== strpos($this->getHeaderLine('Content-Type'), 'application/json')) {
                          return $this->json = json_decode($body, true);
                          }
                          return $body;
                          }
                          }



                        2. Create Middleware which going to replace Guzzle PSR-7 responses with above Response implementation:



                          <?php

                          $client = new GuzzleHttpClient();

                          /** @var HandlerStack $handler */
                          $handler = $client->getConfig('handler');
                          $handler->push(GuzzleHttpMiddleware::mapResponse(function (PsrHttpMessageResponseInterface $response) {
                          return new GuzzleHttpPsr7JsonAwareResponse(
                          $response->getStatusCode(),
                          $response->getHeaders(),
                          $response->getBody(),
                          $response->getProtocolVersion(),
                          $response->getReasonPhrase()
                          );
                          }), 'json_decode_middleware');



                        After this to retrieve JSON as PHP native array use Guzzle as always:



                        $jsonArray = $client->get('http://httpbin.org/headers')->getBody();


                        Tested with guzzlehttp/guzzle 6.3.3






                        share|improve this answer


























                          0












                          0








                          0







                          If you guys still interested, here is my workaround based on Guzzle middleware feature:





                          1. Create JsonAwaraResponse that will decode JSON response by Content-Type HTTP header, if not - it will act as standard Guzzle Response:



                            <?php

                            namespace GuzzleHttpPsr7;


                            class JsonAwareResponse extends Response
                            {
                            /**
                            * Cache for performance
                            * @var array
                            */
                            private $json;

                            public function getBody()
                            {
                            if ($this->json) {
                            return $this->json;
                            }
                            // get parent Body stream
                            $body = parent::getBody();

                            // if JSON HTTP header detected - then decode
                            if (false !== strpos($this->getHeaderLine('Content-Type'), 'application/json')) {
                            return $this->json = json_decode($body, true);
                            }
                            return $body;
                            }
                            }



                          2. Create Middleware which going to replace Guzzle PSR-7 responses with above Response implementation:



                            <?php

                            $client = new GuzzleHttpClient();

                            /** @var HandlerStack $handler */
                            $handler = $client->getConfig('handler');
                            $handler->push(GuzzleHttpMiddleware::mapResponse(function (PsrHttpMessageResponseInterface $response) {
                            return new GuzzleHttpPsr7JsonAwareResponse(
                            $response->getStatusCode(),
                            $response->getHeaders(),
                            $response->getBody(),
                            $response->getProtocolVersion(),
                            $response->getReasonPhrase()
                            );
                            }), 'json_decode_middleware');



                          After this to retrieve JSON as PHP native array use Guzzle as always:



                          $jsonArray = $client->get('http://httpbin.org/headers')->getBody();


                          Tested with guzzlehttp/guzzle 6.3.3






                          share|improve this answer













                          If you guys still interested, here is my workaround based on Guzzle middleware feature:





                          1. Create JsonAwaraResponse that will decode JSON response by Content-Type HTTP header, if not - it will act as standard Guzzle Response:



                            <?php

                            namespace GuzzleHttpPsr7;


                            class JsonAwareResponse extends Response
                            {
                            /**
                            * Cache for performance
                            * @var array
                            */
                            private $json;

                            public function getBody()
                            {
                            if ($this->json) {
                            return $this->json;
                            }
                            // get parent Body stream
                            $body = parent::getBody();

                            // if JSON HTTP header detected - then decode
                            if (false !== strpos($this->getHeaderLine('Content-Type'), 'application/json')) {
                            return $this->json = json_decode($body, true);
                            }
                            return $body;
                            }
                            }



                          2. Create Middleware which going to replace Guzzle PSR-7 responses with above Response implementation:



                            <?php

                            $client = new GuzzleHttpClient();

                            /** @var HandlerStack $handler */
                            $handler = $client->getConfig('handler');
                            $handler->push(GuzzleHttpMiddleware::mapResponse(function (PsrHttpMessageResponseInterface $response) {
                            return new GuzzleHttpPsr7JsonAwareResponse(
                            $response->getStatusCode(),
                            $response->getHeaders(),
                            $response->getBody(),
                            $response->getProtocolVersion(),
                            $response->getReasonPhrase()
                            );
                            }), 'json_decode_middleware');



                          After this to retrieve JSON as PHP native array use Guzzle as always:



                          $jsonArray = $client->get('http://httpbin.org/headers')->getBody();


                          Tested with guzzlehttp/guzzle 6.3.3







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 23 '18 at 10:30









                          andrewandrew

                          10416




                          10416






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f30530172%2fguzzle-6-no-more-json-method-for-responses%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              404 Error Contact Form 7 ajax form submitting

                              How to know if a Active Directory user can login interactively

                              TypeError: fit_transform() missing 1 required positional argument: 'X'