Can anyone give me an example of how I can consume the following web service with php?
http://www.webservicex.net/uszip.asmx?op=GetInfoByZIP
Here's a simple example which uses curl and the GET interface.
$zip = 97219;
$url = "http://www.webservicex.net/uszip.asmx/GetInfoByZIP?USZip=$zip";
$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);
The $result variable contains XML which looks like this
<?xml version="1.0" encoding="utf-8"?>
<NewDataSet>
<Table>
<CITY>Portland</CITY>
<STATE>OR</STATE>
<ZIP>97219</ZIP>
<AREA_CODE>503</AREA_CODE>
<TIME_ZONE>P</TIME_ZONE>
</Table>
</NewDataSet>
Once the XML is parsed into a SimpleXML object, you can get at the various nodes like this:
print $xmlobj->Table->CITY;
If you want to get fancy, you could throw the whole thing into a class:
class GetInfoByZIP {
public $zip;
public $xmlobj;
public function __construct($zip='') {
if($zip) {
$this->zip = $zip;
$this->load();
}
}
public function load() {
if($this->zip) {
$url = "http://www.webservicex.net/uszip.asmx/GetInfoByZIP?USZip={$this->zip}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
$this->xmlobj = simplexml_load_string($result);
}
}
public function __get($name) {
return $this->xmlobj->Table->$name;
}
}
which can then be used like this:
$zipInfo = new GetInfoByZIP(97219);
print $zipInfo->CITY;
I would use the HTTP POST or GET interfaces with curl. It looks like it gives you a nice clean XML output that you could parse with simpleXML.
Something like the following would go along way (warning, totally untested here):
$ch = curl_init('http://www.webservicex.net/uszip.asmx/GetInfoByZIP?USZip=string');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
$xml = curl_exec($ch);
curl_close($ch);
$parsed = new SimpleXMLElement($xml);
print_r($parsed);
Related
I want to read xml data using curl in codeigniter. I have create a helper file which will read data from following url: http://www.ekidata.jp/api/l/11302.xml but problem is that i cannot read the data from this url. plz help
Here is my helper file structure:
if (!function_exists('ekidata')) {
function ekidata($type, $code)
{
$apiurl = 'http://www.ekidata.jp/api/'.$type.'/'.$code.'.xml';
$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);
if ($type == 'l') {
return $xml;
} else {
}
}
}
Here is my controller:
function ekidatatest()
{
$this->load->view('ekidatatest');
}
Here is my view:
<?php echo ekidata('l', 11302);?>
I have tested your code and it works ok, the only issue i see is that you are tryin to echo an object (the returned XML variable), try:
print_r (ekidata('l', 11302));
and you should see all the xml object from the file, then you can loop on the object and get the data you need. So if you want the first station name you can get it like this:
$r = ekidata('l', 11302);
echo $r->station[0]->station_name;
and to loop on all stations:
foreach($r->station as $station) {
echo $station->station_name.'<br/>';
}
I'm currently trying to parse the MapQuest Traffic API, but when I try to display an incident, nothing appears, and if I do "if empty" in php, it returns empty.
Here's the code:
<?php
$mysongs = simplexml_load_file("http://www.mapquestapi.com/traffic/v1/incidents?key=Fmjtd%7Cluuan1u2nh%2C2a%3Do5-96rw5u&callback=handleIncidentsResponse&boundingBox=$_GET[a], $_GET[b], $_GET[c], $_GET[d]&filters=construction,incidents&inFormat=kvp&outFormat=xml");
echo $mysongs->Incidents[0]->Incident[0]->fullDesc;
?>
The parameters I'm passing: ?a=33.352532499999995&b=-118.2324383&c=34.352532499999995&d=-117.2324383.
Thanks in advance!
Here simplexml_load_file not loading all your xml data so, i created a xml file with name test.xml and then loaded data from test.xml. Now you can print data what you need.
<?php
$a = $_GET['a'];
$b = $_GET['b'];
$c = $_GET['c'];
$d = $_GET['d'];
$xml_feed_url = 'http://www.mapquestapi.com/traffic/v1/incidents?key=Fmjtd|luuan1u2nh%2C2a%3Do5-96rw5u&callback=handleIncidentsResponse&boundingBox='.$a.','.$b.','.$c.','.$d.'&filters=construction,incidents&inFormat=kvp&outFormat=xml';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $xml_feed_url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xml = curl_exec($ch);
curl_close($ch);
$xml2 = new SimpleXMLElement($xml);
$xml2->asXML("test.xml");
$xml2->asXML();
$mysongs = simplexml_load_file("test.xml");
print_r($mysongs);
?>
I'm trying to parse an xml file by starting with simplexml_load_file to load the contents. The file comes from a wordpress using an xml feed generated by a .php file.
The problem is it never can load the xml file..I'm not sure what I can do to make this work. Here is the code
<?php
$url = "http://marshallmashup.usc.edu/feed.php";
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$result = curl_exec($ch);
curl_close($ch);
$rss = simplexml_load_string($result);
if( ! $rss = simplexml_load_file($url,NULL, LIBXML_NOERROR | LIBXML_NOWARNING) )
{
echo 'unable to load XML file';
}
else
{
echo 'XML file loaded successfully';
}
?>
First of all after this line:
$result = curl_exec($ch);
you should add this one:
$result = utf8_encode($result);
Said that, you'll have no problems with the function simplexml_load_string($result); which will correctly create a DOM based on the string you give to the function and that is the feed gotten from the php page. You can see the result using var_dump($rss); after the statement $rss = simplexml_load_string($result);.
I am using google spell check in my project and doing everything as suggested in the blogs but it doesn't seem to work for me. Can you please look at this and tell me what I am doing incorrect.
In my JavaScript:
function makeRequest(parameters, svalue) {
console.log("dv-- inside makerequest 1");
console.log("svalue =", svalue);
http_request.onreadystatechange = GetResponse;
http_request.open('POST', 'http://mysite.com/Project/spellify.php?lang=en', true);
data = '<?xml version="1.0" encoding="utf-8" ?>';
data +='<spellrequest textalreadyclipped="0" ignoredups="0" ignoredigits="0" ignoreallcaps="0"><text>';
data += svalue;
data += '</text></spellrequest>';
console.log("data =", data)
http_request.send(data);
}
function GetResponse(){
console.log("dv-- inside GetResponse-1 http_request.readyState =", http_request.readyState)
if (http_request.readyState == 4) {
console.log("dv-- inside GetResponse-2 http_request.status =", http_request.status)
if (http_request.status == 200) {
http_response = http_request.responseText;
console.log("dv --http_response =", http_response)
}
else {
console.log('There was a problem with the request' + '& http_request.status =' + http_request.status );
}
}
}
My PHP Code: spellify.php
$url="http://www.google.com/tbproxy/spell?lang=en&hl=en";
//$data = file_get_contents('php://input');
$data = '<?xml version="1.0" encoding="utf-8" ?><spellrequest textalreadyclipped="0" ignoredups="0" ignoredigits="0" ignoreallcaps="0"><text>hellow </text></spellrequest>';
$data = urldecode($data);
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec ($ch);
curl_close ($ch);
print $contents;
?>
I tried hardcoding the data in my php to make sure data was passed correctly and that is not an issue.
Firefox give an error:
Error: unclosed token
Source File: http://mysite.com/Project/spellify.php?lang=en
Line: 5, Column: 183
Source Code:
$data ='<?xml version="1.0" encoding="utf-8" ?><spellrequest textalreadyclipped="0" ignoredups="0" ignoredigits="0" ignoreallcaps="0"><text>hello thsi is graet</text><`/spellrequest>';
Chrome doesn't give any error, but show below in console:
dv-- inside makerequest 1
spellify.js:419svalue = hello worlda
spellify.js:432dv-- inside GetResponse-1 http_request.readyState = 1
spellify.js:427data = <?xml version="1.0" encoding="utf-8" ?><spellrequest textalreadyclipped="0" ignoredups="0" ignoredigits="0" ignoreallcaps="0"><text>hello worlda </text></spellrequest>
spellify.js:432dv-- inside GetResponse-1 http_request.readyState = 2
spellify.js:432dv-- inside GetResponse-1 http_request.readyState = 3
spellify.js:432dv-- inside GetResponse-1 http_request.readyState = 4
spellify.js:435dv-- inside GetResponse-2 http_request.status = 200
spellify.js:438dv --http_response = <?php
$url="http://www.google.com/tbproxy/spell?lang=en&hl=en";
// $data = file_get_contents('php://input');
$data = '<?xml version="1.0" encoding="utf-8" ?><spellrequest textalreadyclipped="0" ignoredups="0" ignoredigits="0" ignoreallcaps="0"><text>hello thsi is graet</text></spellrequest>';
$data = urldecode($data);
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec ($ch);
curl_close ($ch);
print $contents;
?>
Please suggest what could be corrected to make this work.
Thanks
You are using code from spellify.com, some sort of credit to original developer is appreciated.
1) You have incorrectly modified spellify.php file.
2-a) Spellify basically prepare http-request and parse http-response via Javascript src/spellify.js, so its incorrect to make any changes in spellify.php, rather you should check if you are referencing spellify/src/scriptaculous.js and spellify/src/prototype.js correctly.
2-b) Under same spellify.js you have hardcoded following line incorrectly;
http_request.open('POST', 'http://mysite.com/Project/spellify.php?lang=en', true);
It should be as follows;
http_request.open('POST', 'http://mysite.com/Project/spellify.php?lang=en'+parameters, true);
3) The time when spellify.php was written, there might have no issue with SSL verification, but now it wont return anything unless you ignore the SSL Verification, add following lines in spellify.php, before $contents = curl_exec ($ch);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
Here is sample implementation.
http://amitgandhi.in/2013/01/25/spell-check-utility-using-jquery-and-google-api/
You can add words dictionary. Variable $.SpellChecker.dicWords is a
javascript array which maintain this. You can use your database table
populate this array with existing words. Currently this app is not
connected to database so if you add your words then lifetime of words
would only till page reloads.
Uses google.com/tbproxy/spell api call (Written in PHP)
So from my understanding this should be fairly simple as I should only need to change the original fileget contents code, and the rest of the script should still work? I have commented out the old file get contents and added the curl below.
after changing from file get contents to cURL the code below does not output
//$data = #file_get_contents("http://www.city-data.com/city/".$cityActualURL."-".$stateActualURL.".html");
//$data = file_get_contents("http://www.city-data.com/city/Geneva-Illinois.html");
//Initialize the Curl session
$ch = curl_init();
$url= "http://www.city-data.com/city/".$cityActualURL."-".$stateActualURL.".html";
//echo "$url<br>";
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
//echo $data;
$details = str_replace("\n", "", $data);
$details = str_replace("\r", "", $details);
$detailsBlock = <<<HTML
~<div style='clear:both;'></div><br/><b>(.*?) on our <a href='http://www.city-data.com/top2/toplists2.html'>top lists</a>: </b><ul style='margin:10px;'>(.*?)<div style='bp_bindex'>~
HTML;
$detailsBlock2 = <<<HTML
~<br/><br/><b>(.*?) on our <a href='http://www.city-data.com/top2/toplists2.html'>top lists</a>: </b><ul style='margin:10px;'>(.*?)</ul></td>~
HTML;
$detailsBlock3 = <<<HTML
~<div style='clear:both;'></div><br/><b>(.*?) on our <a href='http://www.city-data.com/top2/toplists2.html'>top lists</a>: </b><ul style='margin:10px;'>(.*?)</ul></td>~
HTML;
preg_match($detailsBlock, $details, $matches);
preg_match($detailsBlock2, $details, $matches2);
preg_match($detailsBlock3, $details, $matches3);
if (isset($matches[2]))
{
$facts = "<ul style='margin:10px;'>".$matches[2];
}
elseif (isset($matches2[2]))
{
$facts = "<ul style='margin:10px;'>".$matches2[2];
}
elseif (isset($matches3[2]))
{
$facts = "<ul style='margin:10px;'>".$matches3[2];
}
else
{
$facts = "More Information to Come...";
}
If you have a problem with your script you need to debug it. For example:
$data = curl_exec($ch);
var_dump($data); die();
Then you will get an output what $data is. Depending on the output you can further decide where to look next for the cause of the malfunction.
The following function works great, just pass it a URL.
function file_get_data($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
TIP: New lines and carriage returns can be replaced with one line of code.
$details = str_replace(array("\r\n","\r","\n"), '', $data);