Dev.W
Dev.W

Reputation: 2370

Laravel GuzzleHTTP XML Response to JSON

I'm making a call the NameCheap's API and they return a XML response.

When trying to output this, I get the response NULL.

Hitting the same API but with the Google Extension POSTMAN I get the results I'm after, am I doing something wrong with the response?

public function testCheck($domains){
    $client = new Client();
    $res = $client->request('GET', 'https://api.namecheap.com/xml.response?ApiUser=(username)&ApiKey=(apikey)&UserName(username)&ClientIp=(ip)&Command=namecheap.domains.check&DomainList=' . $domains);
    $data = json_decode($res->getBody());
    dd($data);
}

I get back

null

Upvotes: 4

Views: 11095

Answers (3)

aethergy
aethergy

Reputation: 733

This is what I'm using to do just that...

Start with the request, like this:

$client = new Client;
$results = $client->request('GET', $this->namecheap_sandbox_url, [
    'query' => [
        'ApiUser' => $this->ApiUser,
        'ApiKey' => $this->SandboxApiKey,
        'UserName' => $this->UserName,
        'Command' => $this->CheckCommand,
        'ClientIp' => $this->ClientIp,
        'DomainList' => $this->DomainList
    ]
]);

$xml = simplexml_load_string($results->getBody(),'SimpleXMLElement',LIBXML_NOCDATA);

Then convert your response, for example:

// json
$json = json_encode($xml);

// array
$array = json_decode($json, true);

// array - dot notation
$array_dot = array_dot($array);

// collection
$collection = collect($array);

Upvotes: 16

Roshan Perera
Roshan Perera

Reputation: 786

Try this

$res = $client->request('GET', 'https://api.namecheap.com/xml.response?ApiUser=(username)&ApiKey=(apikey)&UserName(username)&ClientIp=(ip)&Command=namecheap.domains.check&DomainList=' . $domains)->send()->json();

Upvotes: 0

Nestor Mata Cuthbert
Nestor Mata Cuthbert

Reputation: 1359

You say they return XML, but you are trying to parse it as JSON, that will get null.

Save the body in a variable and dd() that instead of sending it to json_decode() to confirm is XML and that you are getting the response.

After that consider using an XML parser like SimpleXml http://php.net/manual/en/book.simplexml.php

Upvotes: 0

Related Questions