Volevo usare Guzzle 6 per recuperare una risposta xml da un'API remota. Questo è il mio codice:
$client = new Client([ 'base_uri' => '<my-data-endpoint>', ]); $response = $client->get('<URI>', [ 'query' => [ 'token' => '<my-token>', ], 'headers' => [ 'Accept' => 'application/xml' ] ]); $body = $response->getBody();
Vardando il $body
si restituirebbe un object GuzzleHttp\Psr7\Stream
:
object(GuzzleHttp\Psr7\Stream)[453] private 'stream' => resource(6, stream) ... ...
Potrei quindi call $body->read(1024)
per leggere 1024 byte dalla risposta (che leggerebbe in xml).
Tuttavia, mi piacerebbe recuperare l'intera risposta XML dalla mia richiesta, poiché avrò bisogno di analizzarla in seguito utilizzando l'estensione SimpleXML
.
Come posso recuperare al meglio la risposta XML dall'object GuzzleHttp\Psr7\Stream
modo che sia utilizzabile per l'analisi?
Andrebbe il ciclo while
andava?
while($body->read(1024)) { ... }
Apprezzerei il tuo consiglio.
The GuzzleHttp \ Psr7 \ Stream implementa il contratto di Psr \ Http \ Message \ StreamInterface che ha il seguente da offrire:
/** @var $body GuzzleHttp\Psr7\Stream */ $contents = (string) $body;
Lanciare l'object alla string chiamerà il metodo __toString()
sottostante che fa parte dell'interface. Il nome del metodo __toString()
è speciale in PHP .
Poiché l'implementazione in GuzzleHttp "manca" per fornire l'accesso all'effettivo handle di stream, quindi non è ansible utilizzare le funzioni di streaming di PHP che consente operazioni più "stream-lined" ( stream-like ) in circostanze, come stream_copy_to_stream
, stream_get_contents
o file_put_contents
. Questo potrebbe non essere ovvio a prima vista.
L'ho fatto in questo modo:
public function execute ($url, $method, $headers) { $client = new GuzzleHttpConnection(); $response = $client->execute($url, $method, $headers); return $this->parseResponse($response); } protected function parseResponse ($response) { return new SimpleXMLElement($response->getBody()->getContents()); }
La mia applicazione restituisce il contenuto in string con contenuto preparato XML e la richiesta Guzzle invia intestazioni con accetta param application / xml .
$client = new \GuzzleHttp\Client(); $response = $client->request('GET', $request_url, [ 'headers' => ['Accept' => 'application/xml'], 'timeout' => 120 ])->getBody()->getContents(); $responseXml = simplexml_load_string($response); if ($responseXml instanceof \SimpleXMLElement) { $key_value = (string)$responseXml->key_name; }
$client = new \GuzzleHttp\Client(); $response = $client->request('GET', 'your URL'); $response = $response->getBody()->getContents(); return $response;