PHP How to hit a url and download its xml - php

I am trying to send this query:
http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK
To a web service and pull down and parse a bunch of fields there, namely these:
// 1) totalResultsCount
// 2) name
// 3) lat
// 4) lng
// 5) countryCode
// 6) countryName
// 7) adminName1 - gives full state name
// 8) adminName2 - owner of the park.
I am doing this:
$query_string = "http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK";
Could someone please provide the right code to loop through the results and get values?

Since the response is XML, you can use SimpleXML:
$url = "http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK";
$xml = new SimpleXMLElement($url, null, true);
echo "totalResultsCount: " . $xml->totalResultsCount . "<br />";
foreach($xml->geoname as $geoname) {
echo $geoname->toponymName . "<br />";
echo $geoname->lat . "<br />";
echo $geoname->countryCode . "<br />";
echo $geoname->countryName . "<br />";
echo $geoname->adminName1 . "<br />";
echo $geoname->adminName2 . "<br />";
}
Which will displays the results as follows:
totalResultsCount: 225
Glacier Bay National Park and Preserve
58.50056
US
United States
Alaska
US.AK.232
...

Firstly, looks like that web service is returning XML rather than JSON. You can use SimpleXML to parse that out.
Secondly, you may want to check out curl
An Example:
$ch = curl_init("http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$content = curl_exec($ch);
curl_close($ch);

fopen will give you a resource, no the file. Since you're doing a json decode, you'll want to just the whole thing as a string. Easiest way to do this is file_get_contents.
$query = 'http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK';
$response = file_get_contents($query);
// You really should do error handling on the response here.
$decoded = json_decode($response, true);
echo '<p>Decoded: '.$decoded['lat'].'</p>';

Related

Discord oAuth2 API ratelimit triggered without any (known) cause

First question! Woho!
I'm currently coding a Dashboard for a Discord bot in PHP.
Recently, when trying to select a server, it would only display 3 malfunctioning items. So I checked the complete array using print_r() and it turned out it rate-limited me.
Now, I got no idea why that happened, as I'm the only person on the server. So what am I doing wrong? Here is the code for listing the selection page:
$all = DiscordAPI("/users/#me/guilds");
foreach ($all as $guild) {
echo "<a href='/?server=" . $guild['id'] . "'><p>";
if ($guild['icon']) {
if (substr($guild['icon'], 0, 2) == "a_") {
echo "<img class='server-icon' src='https://cdn.discordapp.com/icons/" . $guild['id'] . "/" . $guild['icon'] . ".gif?size=64'>";
} else {
echo "<img class='server-icon' src='https://cdn.discordapp.com/icons/" . $guild['id'] . "/" . $guild['icon'] . ".webp?size=64'>";
}
} else {
$words = explode(" ", $guild['name']);
$acronym = "";
foreach ($words as $w) {
$acronym .= $w[0];
}
echo "<img class='server-icon' src='https://cdn.statically.io/avatar/s=64/" . $acronym . "'>";
}
echo $guild['name'];
echo "</p></a>";
}
And here is the code for the DiscordAPI() function:
function DiscordAPI($endpoint)
{
if (!$_SESSION['token']) {
die("No token provided");
}
$ch = curl_init("https://discord.com/api" . $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Authorization: Bearer " . $_SESSION['token']
));
$data = curl_exec($ch);
curl_close($ch);
return json_decode($data, true);
}
There are 2 API calls before this code to verify that there is a valid token.
Quick sidenote: I got Autism, so I might understand stuff a bit differently. Don't be scared to ask if I worded something hard to understand. Thank you for trying to understand me.

Alternative to curl_init()?

I'm trying to debug some code using either of these two intrepreters. The code below runs on my GoDaddy site and produces the appropirate output arrays. But, won't run in either of these intrepreters.
Is there a way to modify this code to run in the intrepreters so I can get past line 2 of the code? I inclcuded phpinfo(INFO_MODULES); at the end as an aid.
OR do you know of an online intrepreter that will run this code?
https://3v4l.org/
http://www.runphponline.com/
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = '';
curl_setopt($ch, CURLOPT_URL, "https://api.iextrading.com/1.0/stock/market/batch?symbols=aapl,tsla,ge&types=quote,earnings,stats");
$data = curl_exec($ch);
curl_close($ch);
$data = json_decode($data, true);
// debug -------------------------------
echo ' - ';
echo (count($data)); // number of elements
echo " - " . "<br />\n";
var_dump_pre($data); // dump the array
echo "-" . "<br />\n";
echo "xxxxxxxxxxxxxx-" . "<br />\n";
function var_dump_pre($mixed = null) {
echo '<pre>';
var_dump($mixed);
echo '</pre>';
return null;
}
phpinfo(INFO_MODULES);
?>
http://php.net/manual/en/curl.installation.php
It looks like there are some dependancies that you have to install to use curl_init.
It looks like some poor sap did the work for you at http://phpfiddle.org/
Your code works there.
Since the code ran on my GoDaddy site I was able to copy the data returned from the '$data = curl_exec($ch);' insruction and assign it to a variable name at the start of the code I'm trying to debug. So, the code I'm trying to debug starts out with the intended incomimg data (and doesn't have to go get it). I can now continue to use any of these three online intrepreters:
https://3v4l.org/
http://www.runphponline.com/
http://phpfiddle.org/

How to use AWS SDK PHP for AWSECommerceService

I have to use following API URL to fetch Books information (found here)-
http://webservices.amazon.com/onca/xml?
Service=AWSECommerceService
&Operation=ItemLookup
&ResponseGroup=Large
&SearchIndex=All
&IdType=ISBN
&ItemId=076243631X
&AWSAccessKeyId=[Your_AWSAccessKeyID]
&AssociateTag=[Your_AssociateTag]
&Timestamp=[YYYY-MM-DDThh:mm:ssZ]
&Signature=[Request_Signature]
I can use PHP SDK for this, I could not find any doc on how to achieve this using SDK.
EDIT
Following this & this links, I have written following code-
<?php
date_default_timezone_set('UTC');
$ItemId = 1603843698;
$ResponseGroup = 'Offers';
//$Timestamp = gmdate("Y-M-DTh:m:sZ");
$Timestamp = gmdate("Y-m-d\TH:i:s\Z");
$AWSAccessKeyId = "EXAMPLEEXAMPLE";
$associateTag = "something-10";
echo $Timestamp;
echo "<br />";
$str = "GET\n
webservices.amazon.com\n
/onca/xml\n
AWSAccessKeyId=".$AWSAccessKeyId."&AssociateTag=".$associateTag."&ItemId=".$ItemId."&Operation=ItemLookup&ResponseGroup=".$ResponseGroup."&Service=AWSECommerceService&Timestamp=".urlencode($Timestamp);
$str = urlencode(base64_encode(hash_hmac("sha256",$str,'my secrete',true)));
$url = "http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&Operation=ItemLookup&ResponseGroup=Offers&IdType=ASIN&ItemId=".$ItemId."&AssociateTag=ebooksprices-20&AWSAccessKeyId=".$AWSAccessKeyId."&Timestamp=".urlencode($Timestamp)."&Signature=".$str;
echo "<br />";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
var_dump($result);
But with no success, I get this output-
2016-07-14T09:50:06Z string(427) " SignatureDoesNotMatchThe request
signature we calculated does not match the signature you provided.
Check your AWS Secret Access Key and signing method. Consult the
service documentation for
details.34b23224-4750-46c7-8f75-929239f955de"
Any help will be appreciated.
Thanks
Finally I got time to post my working code-
$ItemId = $_GET['isbn'];
$ResponseGroup = 'Offers';
//$Timestamp = gmdate("Y-M-DTh:m:sZ");
//date_default_timezone_set('America/Los_Angeles');
$Timestamp = gmdate("Y-m-d\TH:i:s\Z");
$AWSAccessKeyId = "/your key/";
$AssociateTag = "/your-tag/";
$Version = "2013-08-01";
//echo $Timestamp;
//echo "<br />";
$str = "Service=AWSECommerceService&Operation=ItemLookup&ResponseGroup=".$ResponseGroup."&IdType=ASIN&ItemId=".urlencode($ItemId)."&AssociateTag=".$AssociateTag."&AWSAccessKeyId=".$AWSAccessKeyId."&Timestamp=".urlencode($Timestamp);
$ar = explode("&", $str);
//var_dump($ar);
natsort($ar);
//var_dump($ar);
$str = "GET
webservices.amazon.com
/onca/xml
";
$str .= implode("&", $ar);
//echo $str;
//echo "<br />";
$str = urlencode(base64_encode(hash_hmac("sha256",$str,'/your secret/',true)));
$url = "http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&Operation=ItemLookup&ResponseGroup=Offers&IdType=ASIN&ItemId=".$ItemId."&AssociateTag=your-tag&AWSAccessKeyId=".$AWSAccessKeyId."&Timestamp=".urlencode($Timestamp)."&Signature=".$str;
//echo "<br />";
//echo $url;
//echo "<br />";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
//var_dump($result);
$xml=simplexml_load_string($result) or die("Error: Cannot create object");
echo "<h1>AMAZON API</h1><pre>";
print_r($xml);
This code returns the response in XML format.
Thanks
The AWS SDK's does currently not support the Amazon Product Advertising API.
For implementation there's a PHP code example provided by Amazon on this page: Implementing a Product Advertising API Request
For the request signature, follow this documentation: http://docs.aws.amazon.com/AWSECommerceService/latest/DG/rest-signature.html. More specific details on a PHP implementation of the request signing has been answer here before: Amazon Product API returns “SignatureDoesNotMatch”

Scrape some text from another website without any url or special charecters

I'm trying to learn some using of code, and i'm trying to scrape information or some text from another site to my (for personal usage only).
well, for example i want to take information from this site :
http://en.sratim.co.il/tt1150273/ROOM-(2015)/
i'm tried to scrape the year like :
$year = explode( '<span class="yearpronobold">' , $content );
$year_end = explode("</span>" , $year[1] );
but result was :
2015
and i want result only the number 2015
also couldn't scrape the actors
Actors: William H. Macy, Joan Allen (I), Brie Larson, Cas Anvar,
Randal Edwards, Megan Park, Chantelle Chung
it gives me ARAY
can anyone explain me what to do?
i'm tried to search on google bit it didn't gave the right result what i', searching for.
thank you for any help.
include "simple_html_dom.php";
function doStrips($getString) {
$getString = strip_tags($getString);
return $getString!="" ? $getString : "N/A";
}
$mainUrl= "http://en.sratim.co.il/";
$url = "http://en.sratim.co.il/tt1150273/ROOM-(2015)/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close($ch);
$html = new simple_html_dom();
$html->load($server_output);
$releaseYear = $html->find('.yearpronobold');
$actorDetails = $html->find('a[itemprop="actors"]');
$directorDetails= $html->find('a[itemprop="director"]');
$getDuration = $html->find('time[itemprop="duration"]');
$publishedDate = $html->find('time[itemprop="datePublished"]');
$getGenre = $html->find('span[itemprop="genre"]');
$getImage = $html->find('img[itemprop="image"]');
//print_r($getImage);
echo "Release Year - ".doStrips($releaseYear[0]->children(0))."<br />";
echo "Actor(s) - ".doStrips(implode(", ",$actorDetails))."<br />";
echo "Director - ".doStrips(implode(", ",$directorDetails))."<br />";
echo "Duration - ".doStrips(implode(", ",$getDuration))."<br />";
echo "Published Date - ".doStrips(implode(", ",$publishedDate))."<br />";
echo "Genre - ".doStrips(implode(", ",$getGenre))."<br />";
echo "Image - <img src='".$mainUrl.$getImage[0]->attr["src"]."' /><br />";
Before all, you need to check whether php_curl is enabled on your server.
http://php.net/manual/en/curl.examples-basic.php tutorial on PHP_CURL.
here is the output what i received..

Highrise API - how to work with XML and manipulate variables

Using curl with an api token and getting the XML elements into working variables or to at least view in html format.
Here is the code used that is doing a vardump:
$curl = curl_init('https://mywebsite.highrisehq.com/people.xml');
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_USERPWD,'myapitoken12345:x');
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,0);
$data = curl_exec($curl);
curl_close($curl);
$people_xml = new SimpleXMLElement($data);
var_dump($people_xml);
When doing the var_dump, the output isn't something I am familiar with.
object(SimpleXMLElement) #1 (2) {
["#attributes"]=> array(1) {
["type"]=> string(5) "array" }
["person"]=> array(128) { ... etc. etc. etc...
The XML structure that HighriseHQ.com shows is like this for clues on how to retrieve elements.
<people type="array">
<person>
<first-name>John</first-name>
</person>
<person>
<first-name>Jane</first-name>
</person>
</people>
.... etc. etc.
How or where do I translate the part that says $people = simplexml_load_string($xml); into variables that I can work with? Eventually I want to either display, edit, or store those people as i'll be syncing a website database with highrise - so that notes, and contacts aren't outdated.
Found the solution.
$curl = curl_init('https://my_website_goes_here.highrisehq.com/people.xml');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_USERPWD, 'my_api_token_goes_here:x');
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($curl);
curl_close($curl);
$people_xml = new SimpleXMLElement($data);
foreach($people_xml->person as $person) {
echo "<strong>" . $person->{'first-name'} . " " . $person->{'last-name'} . "</strong><br />";
echo "Title: " . $person->{'title'} . "<br />";
echo "Background: " . $person->{'background'} . "<br />";
echo "Email: " . $person->{'email-address'} . "<br />";
echo "ID: " . $person->id . "<br /><br />";
}

Categories