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.
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>';
Related
This is my code to fetch api
$apiurl = "https://class.cvcngr.in/bigbluebutton/api/create?allowStartStopRecording=true&attendeePW=ap&autoStartRecording=false&meetingID=random-1495797&moderatorPW=mp&name=random-1495797&record=false&voiceBridge=74999&welcome=%3Cbr%3EWelcome+to+%3Cb%3E%25%25CONFNAME%25%25%3C%2Fb%3E%21&checksum=ad1f82091f78ee18673f9c5be36df9eef7860187";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $apiurl);
$response = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($response);
echo $xml;
In the above, I have used an apiurl which stores URL of API. this is my custom API and there is a test API provided by the service provider
$apiurl2 "http://test-install.blindsidenetworks.com/bigbluebutton/api/create?allowStartStopRecording=true&attendeePW=ap&autoStartRecording=false&meetingID=random-9370670&moderatorPW=mp&name=random-9370670&record=false&voiceBridge=79891&welcome=%3Cbr%3EWelcome+to+%3Cb%3E%25%25CONFNAME%25%25%3C%2Fb%3E%21&checksum=0aae50d2d079fd67138a7b266837f6b0112166b5";
Bothe the URL gives the same response but I can get data only when I use apiurl2. when I use the first one there is no response. but when I use in the browser directly there is no issues
It works just fine, the $xml variable is a SimpleXMLElement instance. echo tries to print a string. You can print all of its contents with var_dump($xml) and access its elements directly with an object operator: echo $xml->dialNumber and even loop thru them:
<?php
$apiurl = "https://class.cvcngr.in/bigbluebutton/api/create?allowStartStopRecording=true&attendeePW=ap&autoStartRecording=false&meetingID=random-1495797&moderatorPW=mp&name=random-1495797&record=false&voiceBridge=74999&welcome=%3Cbr%3EWelcome+to+%3Cb%3E%25%25CONFNAME%25%25%3C%2Fb%3E%21&checksum=ad1f82091f78ee18673f9c5be36df9eef7860187";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $apiurl);
$response = curl_exec($ch);
$xml = simplexml_load_string($response);
// var_dump($xml);
// echo 'Dial number: ' . $xml->dialNumber;
foreach ($xml as $key => $value) {
echo "{$key}: {$value}\n";
}
curl_close($ch);
I am new to PHP and have been trying to access to the API for the past 2 hours. Everytime i request for the json object, it kept giving me null. I am sure i filled up the URL and Accountkey correctly. Can comeone please correct me if i did anything wrong with the code below. Thank you.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'http://urlxxxxxxxx.com');
$header = array(
'AccountKey:' => 'xxxx',
'Accept:' => 'application/json');
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);
$obj = json_decode($result);
curl_close($ch);
print "<pre>";
print_r($obj);
print "</pre>";
?>
Try to set CURL http headers like this, not as php array key=>value pattern.
$header = array(
'AccountKey: xxxx',
'Accept:application/json'
);
I have built a custom api using php, its a simple api that works by posting xml data.
The code that I have working to post to the api is:
<?php
$xml_data = '<document>
<first>'.$first.'</first>
<last>'.$last.'</last>
<email>'.$email.'</email>
<phone>'.$phone.'</phone>
<body>TEST</body>
</document>';
$URL = "url";
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
$Response = curl_exec($ch);
curl_close($ch);
echo "Responce= ".$responce;
?>
On the other side, the code the above posts to:
<?php
$postdata = file_get_contents("php://input");
$xml = simplexml_load_string($postdata);
$first = $xml->first;
$last = $xml->last;
$email = $xml->email;
$phone = $xml->phone;
?>
Then I take those php variables and send to a database.. ALL THIS CODE IS WORKING!!
But my questions is: How do I send a response back to the posting side?
How do I use curl_init to send to curl_exec?
Any help would be great! Thank you
Jason
I think you want:
echo "Responce= ".$Response;
^^^
To return a response you'd do the same as you would for any other content, set a header and echo your output. For example, to return an xml response, from the script handling the post data do the following
<?php
$postdata = file_get_contents("php://input");
$xml = simplexml_load_string($postdata);
$first = $xml->first;
$last = $xml->last;
$email = $xml->email;
$phone = $xml->phone;
// do your db stuff
// format response
$response = '<response>
<success>Hello World</success>
</response>';
// set header
header('Content-type: text/xml');
// echo xml identifier and response back
echo chr(60).chr(63).'xml version="1.0" encoding="utf-8" '.chr(63).chr(62);
echo $response;
exit;
?>
You should see the response returned from curl_exec()
I want to read XML data from a URL. I have the URL as follows:
http://www.arrowcast.net/fids/mco/fids.asp?sort=city&city=&number=&airline=&adi=A
Here is my code:
$Url="http://www.arrowcast.net/fids/mco/fids.asp?sort=city&city=&number=&airline=&adi=A";
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $Url);
$output = curl_exec($ch);
$resultCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL resource, and free system resources
curl_close($ch);
Could anyone please tell me how to read xml data?
Here is some sample code (XML parsing module may not be available on your PHP installation):
<?php
$url="http://www.arrowcast.net/fids/mco/fids.asp?sort=city&city=&number=&airline=&adi=A";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url); // get the url contents
$data = curl_exec($ch); // execute curl request
curl_close($ch);
$xml = simplexml_load_string($data);
print_r($xml);
?>
The variable $xml now is a multi-dimensional key value array and you should easily be able to figure out how to get the elements from there.
// the SAX way:
XMLReader myReader = XMLReaderFactory.createXMLReader();
myReader.setContentHandler(handler);
myReader.parse(new InputSource(new URL(url).openStream()));
// or if you prefer DOM:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL(url).openStream());
This is the demo of how to get channel id from rss feed of youtube in which i read xml data from url using curl.
$channel_id = 'XXXXXXXX'; // put the channel id here
//using curl
$url = 'https://www.youtube.com/feeds/videos.xml?channel_id='.$channel_id.'&orderby=published';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$response = curl_exec($ch);
curl_close($ch);
$response=simplexml_load_string($response);
$json = json_encode($response);
$youtube= json_decode($json, true);
$count = 0;
if(isset($youtube['entry']['0']) && $youtube['entry']['0']!=array())
{
foreach ($youtube['entry'] as $k => $v) {
$yt_vids[$count]['id'] = str_replace('http://www.youtube.com/watch?v=', '', $v['link']['#attributes']['href']);
$yt_vids[$count]['title'] = $v['title'];
$count++;
}
}
else
{
$yt_vids[$count]['id']=str_replace('http://www.youtube.com/watch?v=', '', $youtube['entry']['link']['#attributes']['href']);
$yt_vids[$count]['title']=$youtube['title'];
}
echo "<pre>";
print_r($yt_vids);
I saw this post on consuming a web service using CURL: Consume WebService with php
and I was trying to follow it, but haven't had luck. I uploaded a photo of the web service I'm trying to access. How would I formulate my request given the example below, assuming the URL was:
https://site.com/Spark/SparkService.asmx?op=InsertConsumer
I attempted this, but it just returns a blank page:
$url = 'https://xxx.com/Spark/SparkService.asmx?op=InsertConsumer?NameFirst=Joe&NameLast=Schmoe&PostalCode=55555&EmailAddress=joe#schmoe.com&SurveyQuestionId=76&SurveyQuestionResponseId=1139';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
$xmlobj = simplexml_load_string($result);
print_r($xmlobj);
Really, you should probably look at the SOAP extension. If it is not available or for some reason you must use cURL, here is a basic framework:
<?php
// The URL to POST to
$url = "http://www.mysoapservice.com/";
// The value for the SOAPAction: header
$action = "My.Soap.Action";
// Get the SOAP data into a string, I am using HEREDOC syntax
// but how you do this is irrelevant, the point is just get the
// body of the request into a string
$mySOAP = <<<EOD
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope>
<!-- SOAP goes here, irrelevant so wont bother writing it out -->
</soap:Envelope>
EOD;
// The HTTP headers for the request (based on image above)
$headers = array(
'Content-Type: text/xml; charset=utf-8',
'Content-Length: '.strlen($mySOAP),
'SOAPAction: '.$action
);
// Build the cURL session
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $mySOAP);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Send the request and check the response
if (($result = curl_exec($ch)) === FALSE) {
die('cURL error: '.curl_error($ch)."<br />\n");
} else {
echo "Success!<br />\n";
}
curl_close($ch);
// Handle the response from a successful request
$xmlobj = simplexml_load_string($result);
var_dump($xmlobj);
?>
The service requires you to do a POST, and you're doing a GET (curl's default for HTTP urls) instead. Add this:
curl_setopt($ch, CURLOPT_POST);
and add some error handling:
$result = curl_exec($ch);
if ($result === false) {
die(curl_error($ch));
}
This is the best answer because using this once you need to login then
get some data from webservices(third party site data).
$tmp_fname = tempnam("/tmp", "COOKIE"); //create temporary cookie file
$post = array(
'username=abc#gmail.com',
'password=123456'
);
$post = implode('&', $post);
//login with username and password
$curl_handle = curl_init ("http://www.example.com/login");
//create cookie session
curl_setopt ($curl_handle, CURLOPT_COOKIEJAR, $tmp_fname);
curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $post);
$output = curl_exec ($curl_handle);
//Get events data after login
$curl_handle = curl_init ("http://www.example.com/events");
curl_setopt ($curl_handle, CURLOPT_COOKIEFILE, $tmp_fname);
curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($curl_handle);
//Convert json format to array
$data = json_decode($output);
echo "Output : <br> <pre>";
print_r($data);
echo "</pre>";