Read xml data from url using curl and php - php

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);

Related

Can't fetch XML response in PHP

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);

file_get_contents phase XML

Trying to run file_get_contents from http://66.85.14.212:7254
Anyone have any suggestions how I could do this to query specific values?
I am getting the value by given code(it's working properly.):-
<?php
$url="http://66.85.14.212:7254/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($data);
echo "<pre>";
print_r($xml);
//for single variable you can write
echo $xml->Name;
?>

Retrieve JSON using PHP from a URL

I am trying to hit an API and get some JSON back. I can’t seem to figure out what I am doing wrong here. I am getting null as the output.
Here is my PHP code:
<?php
$query_string_full = 'https://api.cityofnewyork.us/calendar/v1/search.htm?app_id=39563317lalaland&app_key=somethingsomething&categories=City%20Government%20Office';
$json = file_get_contents($query_string_full);
$obj = json_decode($json);
echo '<pre>'. json_encode($obj, JSON_PRETTY_PRINT) .'</pre>';
?>
The function file_get_contents doesn’t work with https. You should use the cURL functions instead.
<?php
$query_string_full = 'https://api.cityofnewyork.us/calendar/v1/search.htm?app_id=39563317&app_key=8396021a9bde2aad2eaf8ca9dbeca353&categories=City%20Government%20Office';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $query_string_full);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$json = curl_exec($ch);
curl_close($ch);
$obj = json_decode($json);
echo '<pre>'. json_encode($obj, JSON_PRETTY_PRINT) .'</pre>';
?>
I made this little function to return the json from a few different apis. You need to be using curl.
function exposeJSON ($apiUrl) {
$json_url = $apiUrl;
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $json_url);
// Built in authentication if needed.
//curl_setopt($ch, CURLOPT_USERPWD, "$USER:$PASS");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
// grab URL and pass it to the browser
$response = curl_exec($ch);
$return = json_decode($response[0], true);
// close cURL resource, and free up system resources
curl_close($ch);
return $return;
}
So you could do something like
$apiData = exposeJSON('urltoapi');
echo $apiData; // Should be the json.

php - using curl to consume this web service

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>";

php youtube json decode

I tried to use JSON decode to get the youtube API feed. However, when I paste the JSON result in http://www.jsonlint.com/ I noticed something like
"media$group": {
"media$category": [
Unfortunately some symbols are rejected by php. Here is my code, I tried to remove this $ symbol, but maybe not success. How do I solve this?
$url = 'http://gdata.youtube.com/feeds/api/videosq=football&orderby=published&v=2&alt=json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
$body1 = curl_exec($ch);
$body = str_replace('$','', $body1);
curl_close($ch);
$data = json_decode($body);
foreach ($data->feed->entry as $result) {
...
}
Your problem is the usage of PHP identifiers to access the contents. The simplest solution here would be to get an array instead of an object:
$data = json_decode ( $json , $assoc = true );
This allows access to fields with:
echo $result['media$group']['media$description'];
If you want to keep the object syntax, that's possible with this kludge:
echo $result->{'media$group'}->{'media$category'};
(But arrays are safer here. You don't get a fatal error should the format change and properties be absent.)
This work:
<?php
$url = 'http://gdata.youtube.com/feeds/api/videos?q=football&orderby=published&v=2&alt=json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
$body1 = curl_exec($ch);
$body = str_replace('$','', $body1);
curl_close($ch);
$data = json_decode($body);
foreach ($data->feed->entry as $result) {
var_dump($result);
}
?>

Categories