PHP [function.file-get-contents]: Failed to open stream - php

This is really annoying me, the php script was working and returning the weather from open weather map but literally all of a sudden the php script takes forever to execute and the following error is produced:
Warning: file_get_contents(http://api.openweathermap.org/data/2.5/weather?lat=&lon=&units=metric&cnt=7&lang=en&key=f38a36af9e4965dd5192ba4282abe070) [function.file-get-contents]: failed to open stream: Connection timed out in /xxx/xxx/public_html/fullweather.php on line 15
Any help would be appreciated. The php script can be viewed below. Only the beginning is important (first 18 lines) but I have included the full thing.
<?php
$lat = $_POST["latitude"];
$lon = $_POST["longitude"];
$url="http://api.openweathermap.org/data/2.5/weather?lat=".$lat."&lon=".$lon."&units=metric&cnt=7&lang=en&key=f38a36af9e4965dd5192ba4282abe070";
// Make call with cURL
$session = curl_init($url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);
$json=file_get_contents($url);
$data=json_decode($json,true);
class weatherdata
{
public $temp = "";
public $weather = "";
public $clouds = "";
public $area = "";
public $humidity = "";
public $humidpressure = "";
public $weatherdesc = "";
public $tempmin = "";
public $tempmax = "";
public $windspeed = "";
public $winddirec = "";
}
$data1 = $data['main']['temp'];
$data2 = $data['weather'][0]['main'];
$data3 = $data['clouds']['all'];
$data4 = $data['name'];
$data5 = $data['main']['humidity'];
$data6 = $data['main']['pressure'];
$data7 = $data['weather'][0]['description'];
$data8 = $data['main']['temp_min'];
$data9 = $data['main']['temp_max'];
$data10 = $data['wind']['speed'];
$data12 = $data['wind']['deg'];
$weatherdata = new weatherdata();
$weatherdata->temp = $data1;
$weatherdata->weather = $data2;
$weatherdata->clouds = $data3;
$weatherdata->area = $data4;
$weatherdata->humidity = $data5;
$weatherdata->humidpressure = $data6;
$weatherdata->weatherdesc = $data7;
$weatherdata->tempmin = $data8;
$weatherdata->tempmax = $data9;
$weatherdata->windspeed = $data10;
$weatherdata->winddirec = $data12;
$output[] = $weatherdata;
print(json_encode($output));
?>

I think the API was just down, cause the link is working for me right now.
Try one more time.

May be the API had change it's url by the time. Try to check the documentation for any updated information. I think that they could change it and your code couldnt find because this $url doesn't exist anymore.

i added https instead of http in url and it worked.
so maybe change http in url like this url.
$url="https://api.openweathermap.org/data/2.5/weather?lat=".$lat."&lon=".$lon."&units=metric&cnt=7&lang=en&key=f38a36af9e4965dd5192ba4282abe070";
Edit
Also you should not show your api key to anyone as some one can use it.

Related

PHP Function - Convert HTML form input into resuable function for multiple inputs

I'm using the Zillow API in order to get some data from user inputs. So far I've been able to correctly use the API to get the desired data from a single input.
The issue I'm running into is when I try and convert my simple block of code into a function that I can reuse multiple times with multiple inputs.Eventually, I want the user to be able to uploaded a CSV file or something and run this function through multiple inputs.
Below is my code that is functioning properly:
HTML
<form action="logic.php" method="post">
<p>Address: <input type="text" name="address"></p>
<p>City/State: <input type="text" name="csz"></p>
<input type="submit">
</form>
PHP
//API Key
$api_key = 'XXXxxXXX';
//User Inputs
$search = $_POST['address'];
$citystate = $_POST['csz'];
//User Inputs Fromatted
$address = urlencode($search);
$citystatezip = urlencode($citystate);
//Get Address ID From API
$url = "http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=".$api_key."&address=".$address."&citystatezip=".$citystatezip;
$result = file_get_contents($url);
$data = simplexml_load_string($result);
$addressID = $data->response->results->result[0]->zpid;
//Get Estimate from API (using adressID)
$estimate_url = "http://www.zillow.com/webservice/GetZestimate.htm?zws-id=".$api_key."&zpid=".$addressID;
$estimate_result = file_get_contents($zurl);
$estimate_data = simplexml_load_string($zresult);
$estimate = $zdata->response->zestimate->amount;
echo $estimate;
Now the issue is when I try and wrap both of these up into two separate functions in order to use them for multiple inputs.
$api_key = 'XXXxxXXX';
//User Inputs
$search = $_POST['address'];
$citystate = $_POST['csz'];
//User Inputs Fromatted
$address = urlencode($search);
$citystatezip = urlencode($citystate);
function getAddressID($ad,$cs){
//Get Address ID From API
$url = "http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=".$api_key."&address=".$ad."&citystatezip=".$cs;
$result = file_get_contents($url);
$data = simplexml_load_string($result);
$addressID = $data->response->results->result[0]->zpid;
return $addressID;
}
$addressID = getAddressID($address, $citystatezip);
function getEstimate($aID){
//Get Estimate from API (using adressID)
$estimate_url = "http://www.zillow.com/webservice/GetZestimate.htm?zws-id=".$api_key."&zpid=".$aID;
$estimate_result = file_get_contents($estimate_url);
$estimate_data = simplexml_load_string($estimate_result);
$estimate = $estimate_data->response->zestimate->amount;
return $estimate;
}
echo getEstimate($addressID); //Calling function doesn't return anything
If essentially I'm doing this same thing as the first PHP example. Why isn't this working from within a function? Did I overlook something?
Ant help on this would be greatly appreciated.
The problem is that you are using the $api_key variable inside both functions, and that variable is not available there. PHP works a bit different then other languages. You can read up on it here: http://php.net/manual/en/language.variables.scope.php
I suggest you extract a function for calling the api. This way you can declare the api key in that function. It also allows you to easier maintain your code (you could improve your api call by adding some error handling or switching to curl or something). The golden rule of a programmer, Don't Repeat Yourself.
The code could look something like this (untested):
//User Inputs
$search = $_POST['address'];
$citystate = $_POST['csz'];
//User Inputs Fromatted
$address = urlencode($search);
$citystatezip = urlencode($citystate);
function callZillow($endpoint, array $params)
{
$params['zws-id'] = 'XXX'; // this would be your api_key
$url = 'http://www.zillow.com/webservice/' . $endpoint . '.htm?' . http_build_query($params);
$result = file_get_contents($url);
return simplexml_load_string($result);
}
function getAddressID($ad, $cs)
{
//Get Address ID From API
$data = callZillow('GetSearchResults', ['address' => $ad, 'citystatezip' => $cs]);
$addressID = $data->response->results->result[0]->zpid;
return $addressID;
}
$addressID = getAddressID($address, $citystatezip);
function getEstimate($aID)
{
//Get Estimate from API (using adressID)
$estimate_data = callZillow('GetZestimate', ['zpid' => $aID]);
$estimate = $estimate_data->response->zestimate->amount;
return $estimate;
}
echo getEstimate($addressID);

Attempting to parse XML/JSON from an API output

OK... I am using PHP 5 (be gentle, still learning PHP). CURL is enabled. Attempting to load XML or JSON output from an API to an object and nothing happens. When I manually execute the URL in question, I get what I am expecting.
Here is my code:
class XmlToJson {
public function Parse ($url) {
$fileContents = file_get_contents($url);
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
$simpleXml = simplexml_load_string($fileContents);
$json = json_encode($simpleXml);
return $json;
}
}
$_MySQLServer = "localhost";
$_MySQLServerUserName = "";
$_MySQLServerPassword = "";
$_MySQLDatabaseName = "";
$_SSActiveWear_UserID = "*****";
$_SSActiveWear_APIKey = "*****";
$_SSActiveWear_APIBaseURL = "https://*****/v2";
$_CategoryURL = "/categories/";
$_StylesURL = "/styles/";
$_ProductsURL = "/products/";
$_SpecsURL = "/specs/";
$_SSActiveWear_MediaType = "xml";
//$_conn = mysqli_connect($_MySQLServer, $_MySQLServerUserName, $_MySQLServerPassword, $_MySQLDatabaseName);
//Insert or Update Categories
$_URL = $_SSActiveWear_APIBaseURL . $_CategoryURL;
$_URL = $_URL . "?mediatype=$_SSActiveWear_MediaType&UserName=$_SSActiveWear_UserID&Password=$_SSActiveWear_APIKey";
$OBJ = simplexml_load_string($_URL);
print_r($OBJ);
What am I doing wrong?
Edit 1
Added the following code:
$xml = simplexml_load_file($_URL) or die("Error: Cannot create object");
print_r($xml);
and it dies. Does that mean that there is something wrong with the code?
Try this :
$OBJ = simplexml_load_string(file_get_contents($_URL));
If you want to know why your code is not working, you are trying to load XML from URL but "simplexml_load_string" loads XML from string.
I FINALLY figured it out... More to the point I finally found a site on Google that helped. It is the first answer in fsockopen with http authentication problem.
So here is the code that works:
file_get_contents("https://$_SSActiveWear_UserID:$_SSActiveWear_APIKey#$_SSActiveWear_APIBaseURL$_CategoryURL/?mediatype=$_SSActiveWear_MediaType");
mediatype can be either json or xml

Error while loading xml file?

Am dynamically loading an xml file and sending request to the api but getting
Warning: DOMDocument::loadXML(): Empty string supplied as input in /home/spotrech/public_html/ but this error is very inconsistent sometime appear sometime don't! I really no idea how to solve this. below is code
$rechargeApiUrl = "http://allrechargeapi.com/apirecharge.ashx?uid=$uid&apikey=$apike&number=$mobileNo&opcode=$opId&amount=$amount&ukey=$uniId&format=xml";
$url = file_get_contents($rechargeApiUrl);
$xmlDoc = new DOMDocument();
$xmlDoc->loadXML(preg_replace('/(<\?xml[^?]+?)utf-16/i', '$1utf-8', $url));
$itemInfo = $xmlDoc->getElementsByTagName('Result'); //returns an object.
$itemCount = $itemInfo->length;
foreach ($itemInfo as $userInfo) {
//Assigning node values to its specified variables.
$ukey = strtolower($userInfo->getElementsByTagName('ukey')->item(0)->childNodes->item(0)->nodeValue);
$status = $userInfo->getElementsByTagName('status')->item(0)->childNodes->item(0)->nodeValue;
$resultCode = $userInfo->getElementsByTagName('resultcode')->item(0)->childNodes->item(0)->nodeValue;
}
$strStatus = strtolower(trim($status));
$strResultCode = trim($resultCode);
$strCode = trim($ukey);
any response will be appreciated.Thank you

Integrating UPS Xml soap feed (PHP)

I am trying to get the xml rate soap feed from UPS working.
Currently I am getting the error "Wrong version" (__Soapcall Exeption) or "0FailureHard10002The XML document is well formed but the document is not valid1" (Respons from server or php).
I took the example provided in the developers toolkit. I tried everything =>
Change soap version to 1.2
Grab wsdl from remote url instead of on
the disk
I double checked the endpoint and userid, accesskey, pass,
...
Does anyone have a working script ?, or even better can someone correct my mistake :)
Code:
<?php
class UpsRate{
private $access,$userid,$passwd,$wsdl,$operation,$endpointurl;
public function __construct() {
$this->setConfig();
}
public function setConfig($is_test = true){
$this->access = sfConfig::get('app_shipping_ups_access');
$this->userid = sfConfig::get('app_shipping_ups_userid');
$this->passwd = sfConfig::get('app_shipping_ups_password');
$this->wsdl = sfConfig::get('sf_data_dir').'/wsdl/ups/RateWS.wsdl';
$this->operation = "ProcessRate";
$this->endpointurl = $is_test?'https://wwwcie.ups.com/ups.app/xml/Rate':'https://onlinetools.ups.com/ups.app/xml/Rate';
}
private function processRate(){
//create soap request
$option['RequestOption'] = 'Shop';
$request['Request'] = $option;
$pickuptype['Code'] = '01';
$pickuptype['Description'] = 'Daily Pickup';
$request['PickupType'] = $pickuptype;
$customerclassification['Code'] = '01';
$customerclassification['Description'] = 'Classfication';
$request['CustomerClassification'] = $customerclassification;
$shipper['Name'] = 'Trutec';
$shipper['ShipperNumber'] = 'Y5562A';
$address['AddressLine'] = array
(
'Ter rivierenlaan 176',
'',
''
);
$address['City'] = 'Antwerp';
//$address['StateProvinceCode'] = 'MD';
$address['PostalCode'] = '2100';
$address['CountryCode'] = 'BE';
$shipper['Address'] = $address;
$shipment['Shipper'] = $shipper;
$shipto['Name'] = 'Imani Imaginarium';
$addressTo['AddressLine'] = '21 ARGONAUT SUITE B';
$addressTo['City'] = 'ALISO VIEJO';
//$addressTo['StateProvinceCode'] = 'CA';
$addressTo['PostalCode'] = '92656';
$addressTo['CountryCode'] = 'US';
$addressTo['ResidentialAddressIndicator'] = '';
$shipto['Address'] = $addressTo;
$shipment['ShipTo'] = $shipto;
$shipfrom['Name'] = 'Trutec';
$addressFrom['AddressLine'] = array
(
'Ter rivierenlaan 176',
'',
''
);
$addressFrom['City'] = 'Deurne';
//$addressFrom['StateProvinceCode'] = 'MD';
$addressFrom['PostalCode'] = '2100';
$addressFrom['CountryCode'] = 'BE';
$shipfrom['Address'] = $addressFrom;
$shipment['ShipFrom'] = $shipfrom;
$service['Code'] = '03';
$service['Description'] = 'Service Code';
$shipment['Service'] = $service;
$packaging1['Code'] = '02';
$packaging1['Description'] = 'Rate';
$package1['PackagingType'] = $packaging1;
$dunit1['Code'] = 'IN';
$dunit1['Description'] = 'cm';
$dimensions1['Length'] = '5';
$dimensions1['Width'] = '4';
$dimensions1['Height'] = '10';
$dimensions1['UnitOfMeasurement'] = $dunit1;
$package1['Dimensions'] = $dimensions1;
$punit1['Code'] = 'KG';
$punit1['Description'] = 'KG';
$packageweight1['Weight'] = '4';
$packageweight1['UnitOfMeasurement'] = $punit1;
$package1['PackageWeight'] = $packageweight1;
$shipment['Package'] = array( $package1 );
$shipment['ShipmentServiceOptions'] = '';
$shipment['LargePackageIndicator'] = '';
$request['Shipment'] = $shipment;
return $request;
}
public function getRate(){
try {
//nitialize soap client
$client = new SoapClient($this->wsdl , array('soap_version' => 'SOAP_1_1','trace' => 1));
//set endpoint url
$client->__setLocation($this->endpointurl);
//create soap header
$usernameToken['Username'] = $this->userid;
$usernameToken['Password'] = $this->passwd;
$serviceAccessLicense['AccessLicenseNumber'] = $this->access;
$upss['UsernameToken'] = $usernameToken;
$upss['ServiceAccessToken'] = $serviceAccessLicense;
$header = new SoapHeader('http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0','UPSSecurity',$upss);
$client->__setSoapHeaders($header);
//get response
return $client->__soapCall($this->operation ,array($this->processRate()));
}
catch(Exception $ex)
{
echo '<pre>';
return print_r($client->__getLastResponse());
echo '</pre>';
}
}
}
?>
The error notifies that your XML is being correctly formatted but you have included one or more elements that are incompatible. Are you able to dump the XML sent ? This may be easier to determine where the error is being detected.
I wouldn't recommend depending on the examples in the UPS documentation to work, they are for illustrative purposes only and probably have not been updated since the first issue.
I had the same issue, and worked this out:
When I would make test calls, they would work. The endpoint I used for the test calls was
https://wwwcie.ups.com/webservices/Rate
However, when I would change to the live calls, then I would receive the wrong version error. That endpoint is:
https://onlinetools.ups.com/webservices
I reviewed the wsdl document, and found near the end a section that looks like this:
<wsdl:port name="RatePort" binding="tns:RateBinding">
<!-- Production URL -->
<!-- <soap:address location="https://onlinetools.ups.com/webservices/Rate"/> -->
<!-- CIE (Customer Integration Environment) URL -->
<soap:address location="https://wwwcie.ups.com/webservices/Rate"/>
</wsdl:port>
I noticed that the live version endpoint was commented out, so I changed the section as follows:
<wsdl:port name="RatePort" binding="tns:RateBinding">
<!-- Production URL -->
<soap:address location="https://onlinetools.ups.com/webservices/Rate"/>
<!-- CIE (Customer Integration Environment) URL -->
<!--<soap:address location="https://wwwcie.ups.com/webservices/Rate"/>-->
</wsdl:port>
I'm not sure this will help anyone else, but this ended up resolving my issues.

Amazon API page number not working

I'm trying to fetch a list of results for a search through Amazon API to list products on my website. Everything works except for specifying the page number that I want to retrieve. It always fetches page 1 for some reason.
$SecretAccessKey = "xxx";
$request['AWSAccessKeyId'] = "xxx";
$request['AssociateTag'] = "xxx";
$request['Timestamp'] = gmdate("Y-m-d\TH:i:s\Z");
$request['ResponseGroup'] = "ItemAttributes,Offers,Images";
$request['ItemPage'] = 1;
$request['Service'] = 'AWSECommerceService';
$request['Version'] = '2011-08-01';
$request['Operation'] = 'ItemSearch';
$request['SearchIndex'] = $search['category_name'];
$request['Keywords'] = $search['text'];
$request['Page'] = 5;
ksort($request); // Sorts in order of key
$Prepend = "GET\nwebservices.amazon.com\n/onca/xml\n";
$String = http_build_query($request);
$PrependString = str_replace('+', '%20', $Prepend . $String);
$Signature = base64_encode(hash_hmac("sha256", $PrependString, $SecretAccessKey, True));
$Signature = urlencode($Signature);
$BaseUrl = "http://webservices.amazon.com/onca/xml?";
$SignedRequest = $BaseUrl . $String . "&Signature=" . $Signature;
// Fetch the generated URL
$xml = simplexml_load_file($SignedRequest);
I've tried with $request['Page'], $request['page'], $request['Pages'] and $request['pages']. None seem to work to pull the correct page. Does anyone know what this parameter is supposed to be named?
Turns out it was ItemPage.
$request['ItemPage'] = 5;

Categories