I am having some issues writing a block of PHP that will allow me to access a web api with credentials. Edit: Current non-functioning code block with proposed changes:
<?php
$agent = array('ID' => '', 'Label' => '');
$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_URL, 'APIurlHere');
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($curl, CURLOPT_USERPWD, 'ID:pass');
curl_setopt($curl, CURLOPT_POSTFIELDS, $agent);
curl_setopt($curl, CUROPT_RETURNTRANSFER, true);
$agent = curl_exec($curl);
curl_close($curl);
var_dump($agent);
I'm honestly at a real loss here, I wouldn't call myself a web developer, but I have had some experience with HTML/asp.net/C#/google polymer, but both web APIs and PHP are new to me.
What I am looking to do is retrieve an agent object from the URL request (which I believe comes back in XML format?) and store that data in a php variable.
Some of the issues I have run into is "error 411" which is asking me to limit the response (although somehow I am not getting that error any more after I added the postfields line, not sure how) and being unable to actually view the xml/agent object I should be getting back.
Updated code:
<?php
$agent = array('ID' => '', 'Label' => '');
$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_URL, 'URL');
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($curl, CURLOPT_USERPWD, 'ID:pass');
curl_setopt($curl, CURLOPT_POSTFIELDS, $agent);
curl_setopt($curl, CUROPT_RETURNTRANSFER, true);
$agent = curl_exec($curl);
$agent = json_decode($agent, true);
curl_close($curl);
var_dump($agent);
print $agent;
The object I am trying to receive is not in XML like I originally thought, but is in json. When I try to view what is in the parsed json var 'agent' all I see is the int value 1.
You have to use the CURLOPT_RETURNTRANSFER
option to get the response from the call.
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$xml = curl_exec($curl);
Now you can parse the XML in $xml
.
This won't work:
echo $agent;
You can't echo an array, you can only echo numbers and strings. If you want to see what's in an array, use
var_dump($agent);