MSU_Bulldog MSU_Bulldog - 6 months ago 33
PHP Question

PHP get XML from URL with credentials

I have a URL that prompts for a username/password to get its data. The data is in XML format. At first I tried to retrieve the data like this:

$url = "http://username:password@[ip-address]:8086/connectioncounts?flat";
$xml = simplexml_load_file($url);
print_r($xml);


After searching for an answer I've come up with this code:

$url = "http://[ip-address]:8086/connectioncounts?flat";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "username:password");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
echo $result;


I'm not getting any data returned on either of these attempts. Could someone tell me what I'm doing wrong?

Answer

You need to change seperate the port from the URL by filling the CURL options in an array like so -

$ch = curl_init(); 

$options = array(CURLOPT_URL => "http://[ip-address]/connectionscounts?flat/<URI>", 
CURLOPT_PORT => "8086", 
CURLOPT_HEADER => "Content-Type:application/xml", 
CURLOPT_USERPWD => "username:password", 
CURLOPT_HTTPAUTH => CURLAUTH_BASIC, 
CURLOPT_RETURNTRANSFER => TRUE 
); 

curl_setopt_array($ch, $options); 
$data = curl_exec($ch); 

$xml = new SimpleXMLElement($data); 
print_r($xml);