0

How can I display the data returned from cURL as an XML document on the page?

Currently I get something like this:

[something] => 189129
[somethingElse] => exampleContent
[somethingElse1] => someMoreExamples
[somethingElse2] => evenMoreExamples

From this code:

$url = "http://example/";

$header[] = 'Accept: application/xml';
$header[] = 'Accept-Encoding: gzip';

$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);

$xmlResponse = new SimpleXMLElement($response);
?>

<?php
print_r('<pre>');
print_r($xmlResponse);
print_r('</pre>');
?>

Is there a way to format the response directly as XML or a way to transform it after with php?

Thanks.

7
  • You want curl to reformat your data to xml? Are you using curl directly or via php, perl etc? Commented Jan 13, 2014 at 19:30
  • I am using cURL via PHP and I want it to be printed on the page like an xml document. Commented Jan 13, 2014 at 19:35
  • Then tag the question with PHP (so it will be seen) and add some php code (so we can help) Commented Jan 13, 2014 at 19:40
  • Hi Adam, thanks for the suggestions. I have added some example code to the post and changed the tag to Php. Commented Jan 13, 2014 at 19:48
  • No worries @Bogdan - welcome to StackOverflow, people are usually friendly and helpful here as long as the question is asked well. I've undone the downvote someone gave you. Commented Jan 13, 2014 at 19:57

1 Answer 1

2

Edit:

If the data you are fetching is already xml, all you need to do is

echo htmlentities($xmlResponse);

Previous answer (for posterity):

I believe you can do something like:

// start your xml with a simple doctype
$xml = new SimpleXMLElement('<?xml version="1.0" standalone="yes"?><data/>');

// loop through each array entry, adding the key/value as a child to 'data'
foreach($response AS $key=>$value)
{
    $xml->addChild($key, $value);
}
// get the xml
$xmlResponse = $xml->asXML();

// output it, encoding the html characters so it displays ok
echo '<pre>';
echo htmlentities($xmlResponse);
echo '</pre>';
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot Adam. I will upvote your answer as soon as I get some reputations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.