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
Related
I want to connect php with tally and I want to store ledger in tally with php any idea?
I got reference from different site like :
1) http://www.tallysolutions.com/website/html/tallydeveloper/integration-capabilities.php
2)http://stackoverflow.com/questions/15717941/how-to-insert-data-into-tally-using-php
But it doesn't fulfill my requirement.
Thanks in advance
It's may help you
// create a new XML document
$doc = new DomDocument('1.0', 'UTF-8');
$envelope = $doc->appendChild($doc->createElement('ENVELOPE'));
//Header Section
$header = $envelope->appendChild($doc->createElement('HEADER'));
$version = $header->appendChild($doc->createElement('VERSION','6.3'));
$import = $header->appendChild($doc->createElement('TALLYREQUEST','Import'));
$type = $header->appendChild($doc->createElement('TYPE','Data'));
$id = $header->appendChild($doc->createElement('ID','All Masters'));
//End Header Section
//Body Section
$body = $envelope->appendChild($doc->createElement('BODY'));
$desc = $body->appendChild($doc->createElement('DESC'));
$static_var = $desc->appendChild($doc->createElement('STATICVARIABLES'));
$dup_combine = $static_var->appendChild($doc->createElement('IMPORTDUPS','##DUPCOMBINE'));
$data = $body->appendChild($doc->createElement('DATA'));
$tally_msg = $data->appendChild($doc->createElement('TALLYMESSAGE'));
//Ledger Data
foreach($contacts_data as $key => $value){
$ledger = $tally_msg->appendChild($doc->createElement('LEDGER'));
$parent=$ledger->appendChild($doc->createElement('PARENT',($value['contacts_types_id']=='1')?'Sundry Debtors':'Sundry Creditors'));
$name=$ledger->appendChild($doc->createElement('NAME',trim(str_replace( "&"," AND ",$value['name']))));
$address=$ledger->appendChild($doc->createElement('ADDRESS',trim(str_replace( "&"," AND ",$value['address']))));
$state=$ledger->appendChild($doc->createElement('STATENAME',trim(str_replace( "&"," AND ",$value['state_name']))));
$pincode=$ledger->appendChild($doc->createElement('PINCODE',$value['pincode']));
/*$ledger_contact=$ledger->appendChild($doc->createElement('LEDGERCONTACT',trim(str_replace( "&"," AND ",$value['contact_person']))));
$phone=$ledger->appendChild($doc->createElement('LEDGERPHONE',$value['phone']));
$fax=$ledger->appendChild($doc->createElement('LEDGERFAX',$value['fax']));
$mobile_no=$ledger->appendChild($doc->createElement('MOBILENO',$value['mobile_no']));
$sales_tax_no=$ledger->appendChild($doc->createElement('SALESTAXNO','23456789'));
$pan_no=$ledger->appendChild($doc->createElement('PANNO','453456789'));*/
$o['contacts_id'][]=$value['id'];
}
//End Ledger and Body Section
//Write the XML nodes
$fp = fopen(public_path()."/xml/import_tally/ledger.xml","wb");
if(fwrite($fp,$doc->saveXML())){
$o['tally_rslt']= shell_exec("curl -X POST tally_server_ip:port --data #".public_path()."/xml/import_tally/ledger.xml");
$o['modified_result']=strpos(preg_replace('/[0-9]+/', '', $o['tally_rslt']),'exists');
}
fclose($fp);
return $o;
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.
i want to get the subscriber count value from this JSON file: http://gdata.youtube.com/feeds/api/users/googlechrome?v=2&alt=json
This is what i did but it's not working.
$youtube_url = json_decode( file_get_contents( 'http://gdata.youtube.com/feeds/api/users/googlechrome?v=2&alt=json' ), true );
$youtube_data = $youtube_url['entry']['yt$statistics']['subscriberCount'];
PHP Code:
function get_yt_subs($username) {
$xmlData = file_get_contents('http://gdata.youtube.com/feeds/api/users/' . strtolower($username));
$xmlData = str_replace('yt:', 'yt', $xmlData);
$xml = new SimpleXMLElement($xmlData);
$subs = $xml->ytstatistics['subscriberCount'];
return($subs);
}
Example of usage:
PHP Code:
get_yt_subs('3moeslam')
I just change the JSON method to XML and everything work fine for me. the question that i wrote work good for #Matt Koskela but not for me. anyway, i'll go a head with this method but i really want to know the problem with the JSON method.
$youtube_url = file_get_contents( 'http://gdata.youtube.com/feeds/api/users/googlechrome';
$youtube_url = str_replace( 'yt:', 'yt', $youtube_url );
$youtube_data = $youtube_url->ytstatistics['subscriberCount'];
I am trying to read a weather feed from Yahoo to my site.
Using the code below I was able to print the xml.
What I really want to achieve now is to put the temperature and image in two different variables
$zipCode = "44418";
$url = "http://weather.yahooapis.com/forecastrss";
$zip = "?w=$zipCode";
$fullUrl = $url . $zip.'&u=c';
$curlObject = curl_init();
curl_setopt($curlObject,CURLOPT_URL,$fullUrl);
curl_setopt($curlObject,CURLOPT_HEADER,false);
curl_setopt($curlObject,CURLOPT_RETURNTRANSFER,true);
$returnYahooWeather = curl_exec($curlObject);
curl_close($curlObject);
print "yahooWeather". $returnYahooWeather;
//$temperature
//$image
You should go ahead and use simplexml or DOM to parse the XML and then you can iterate over the results. With SimpleXML this looks like this:
$zipCode = "44418";
$url = "http://weather.yahooapis.com/forecastrss";
$zip = "?w=$zipCode";
$fullUrl = $url . $zip.'&u=c';
$curlObject = curl_init();
curl_setopt($curlObject,CURLOPT_URL,$fullUrl);
curl_setopt($curlObject,CURLOPT_HEADER,false);
curl_setopt($curlObject,CURLOPT_RETURNTRANSFER,true);
$returnYahooWeather = curl_exec($curlObject);
curl_close($curlObject);
//print "here". $returnYahooWeather;
$xmlobj=simplexml_load_string($returnYahooWeather);
$res = $xmlobj->xpath("//yweather:condition");
$tmp = false;
while(list( , $node) = each($res)) {
$tmp = $node;
}
$attribs = $tmp->attributes();
print "Temperature [".$attribs['temp']."]";
I find it easiest to SimpleXML with PHP.
$xml = simplexml_load_string($returnYahooWeather);
echo $xml->Path->To->Temperature;
It's easy enough, and you can use XPath with SimpleXML :). There are other ways of parsing XML too, as previously mentioned DOMDocument is one of them.
I am trying to purge a file through the MaxCDN API but it's not working. Here's the code I'm using. The print_r doesn't return any result.
function purge() {
date_default_timezone_set('America/Los_Angeles');
$date = date('c');
$apiid = 'myapiid';
$apikey = 'myapi';
$auth_key = hash('sha256', $date.':'.$apikey.':purge');
$url = 'http://softsailor.alexdumitru.netdna-cdn.com/wp-content/themes/ss3/includes/sprite.jpg';
if (!class_exists('IXR_Client')) {
require_once (ABSPATH . WPINC . '/class-IXR.php');
}
$client = new IXR_Client('api.netdna.com','/xmlrpc/cache',80);
$client->timeout = 30;
$client->query('cache.purge', $apiid, $auth_string, $date, $url);
print_r($client->getResponse());
}
I turned debug on and I'm getting the following error
Something went wrong - -32300 : transport error - HTTP status code was not 200
Hey Alex. I work at MaxCDN and here is a code example that I took from our Wiki:
<?php
date_default_timezone_set('America/Los_Angeles');
include("lib/xmlrpc.inc");
$cur = date('c');
$apiKey = 'api-key';
$apiUserId = 'api-user-id';
$namespace = 'cache';
$method = 'purge';
$authString = hash('sha256', $cur . ':' . $apiKey . ':' . $method);
// this is the url to purge
$url= 'http://static.jdorfman.netdna-cdn.com/static/images/frugal-it-logo.png';
$f=new xmlrpcmsg("$namespace.$method", array(php_xmlrpc_encode($apiUserId),
php_xmlrpc_encode($authString), php_xmlrpc_encode($cur),
php_xmlrpc_encode($url)));
$c=new xmlrpc_client("/xmlrpc/cache", "api.netdna.com", 80,'http11');
$r=&$c->send($f);
print_r($r);
?>
If you have any other questions or concerns feel free to get in contact with me: jdorfman at maxcdn dot com
jdorfman's example dumps the entire raw response but if you are like me you want to get it into data objects using php
Here are some helpful tips:
$r->serialize() to access just the raw XML response
to convert to JSON use this:
$xml = simplexml_load_string($r->serialize());
echo json_encode($xml);