Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning a XML response with CURL

Tags:

php

curl

xml

I am passing some parameters via HTTP POST to a webserver.

I am getting a response, but ideally I want a full XML responses, whereas I seem to be only getting a concatenated string. I've tried SimpleXMLElement, but it doesn't seem to do anything, and it isn't returning any XML.

Below is my code:

$post_string = '<?xml version="1.0" encoding="utf-16" ?> 
<ChameleonIAPI>
  <Method>TitleList</Method> 
  <APIKey>D12E9CF3-F742-47FC-97CB-295F4488C2FA</APIKey> 
  <UserName>David</UserName>
  <Filter>
  </Filter>
</ChameleonIAPI>';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"https://jobs.chameleoni.com/PostXML/PostXml.aspx");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
        "Action=postxml&AuthKey=Guest&AuthPassword=KgwLLm7TL6G6&Xml=$post_string");

// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);

$server_output = curl_exec ($ch);

echo $server_output." TEST <br />";
curl_close ($ch);

$oXML = new SimpleXMLElement($server_output);

foreach($oXML->entry as $oEntry){
  echo $oEntry->title . "\n";
}

Here's the page which you can even test the POST and XML.

https://jobs.chameleoni.com/PostXML/PostingXML.html

My XML seems to be ok, as it works on the test page. I assume there is something wrong with my PHP, although I have no idea what that is!

Any help would be lovely!

like image 440
Jack Gleeman Avatar asked Jan 28 '26 05:01

Jack Gleeman


1 Answers

Your code retrieve full XML, to see it write:

echo htmlentities( $server_output );
die();

and in the browser you'll see:

<?xml version="1.0" encoding="utf-16" ?> <ChameleonIAPIResponse>

<Titles><TitleId>1</TitleId><Title></Title><TitleId>6</TitleId><Title>Mr</Title><TitleId>2</TitleId><Title>Mrs</Title><TitleId>3</TitleId><Title>Miss</Title><TitleId>4</TitleId><Title>Ms</Title><TitleId>5</TitleId><Title>Dr</Title><TitleId>43</TitleId><Title>Sir</Title></Titles> </ChameleonIAPIResponse>

The problem is that the browser interpret your output as HTML, so the tag are hidden (see at the browser page source, and you will find your complete XML).

In addition, to send XML as XML, before you have to send appropriate headers:

header( 'Content-type: text/xml' );
echo $server_output;
die();

No other output before and after above code, otherwise your XML will result broken.

If you prefer SimpleXML, you can do this:

$oXML = new SimpleXMLElement( $server_output );
header( 'Content-type: text/xml' );
echo $oXML->asXML();
die();

Also in this case, no output before and after (So comment previous lines).

like image 121
fusion3k Avatar answered Jan 30 '26 18:01

fusion3k