Geocode - curl request - convert associative array into xml - php

I'm trying to convert my geocode lat and lng data into XML so that I can use it:
This is an example of the URL that I am using from the googleapi's:
http://maps.googleapis.com/maps/api/geocode/json?address=1600%20Amphitheatre%20Parkway,%20Mountain%20View,%20CA&sensor=false
My code so far is:
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $request_url);
$contents = curl_exec($c);
curl_close($c);
$xml = json_decode( json_encode( simplexml_load_string( $contents ) ), TRUE );
var_dump($xml, $contents, $c); exit();
This is consistently returning false on the $xml, though the content is being passed back.

You don't have to convert json to xml.
Google services by default provides two types of output. one is JSON and other is XML.
In the url you had mentioned replace the letters 'json' with the letters 'xml' so that it will look like that following and it will give you xml output.
http://maps.googleapis.com/maps/api/geocode/xml?address=1600%20Amphitheatre%20Parkway,%20Mountain%20View,%20CA&sensor=false
Open the above url in a browser and you can see the result in xml.
Here is an excerpt of the sample output i got when i directly gave the url i had mentioned above in the browser.
<GeocodeResponse>
<status>OK</status>
<result>
<type>street_address</type>
<formatted_address>
1600 Amphitheatre Parkway, Mountain View, CA 94043, USA
</formatted_address>
<address_component>
So, in your code you can remove the json functions and directly use $xml = simplexml_load_string( $contents )...
...

$xml = json_decode( json_encode( simplexml_load_string( $contents ) ), TRUE );
You're trying to transform JSON data into XML using simplexml_load_string. If you read the manual for simplexml_load_string, you'll see that $contents should be a "well-formed XML string". In your case, $contents is a string representing JSON data.
If you're wanting XML, you should be accessing this part of the Google API instead. The difference between the two links:
http://maps.googleapis.com/maps/api/geocode/json
http://maps.googleapis.com/maps/api/geocode/xml
Example using SimpleXMLElement:
$output = new SimpleXMLElement($contents);
var_dump($output);

Related

Ebay api, VerifyAddItem is returning errors when i send it xml using cURL

I am having trouble debugging this error i am recieving.
I tested the xml on the ebay developing site to see if it is valid and I recieved no errors However when I attempt to send the xml file I receive an error.
PHP code:
function EbayVerifyAddItem($search)
{
$url= utf8_encode("https://api.ebay.com/ws/api.dll"); //end point
$xmlrequest = temp/xmlfile.xml; // link to xml file
$xml = simplexml_load_file($xmlrequest);
echo"<h3>Ebay Get Category</h3>";
echo "URL: ".$url."<br>";
$headers = array(
'X-EBAY-API-COMPATIBILITY-LEVEL: 901',
'X-EBAY-API-DEV-NAME: productionDeveloperKey',
'X-EBAY-API-SITEID: 3',
'X-EBAY-API-CALL-NAME: VerifyAddItem',
'Content-Type: text/xml');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // set headers using $headers array
curl_setopt($ch, CURLOPT_POST, true); // POST request type
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); // set the body of the POST
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return values as a string, not to std out
$content=curl_exec($ch);
curl_close($ch);
echo "<br><br>";
echo "Path to xml file: ".$xmlrequest."<br>";
echo printf("content: %s",$content);
echo "<br><br>";
return true;
}
xmlfile.xml:
<?xml version="1.0" encoding="utf-8"?>
<VerifyAddItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">
<ErrorLanguage>en_US</ErrorLanguage>
<WarningLevel>High</WarningLevel>
<Item>
<Title>Title</Title>
<Description>Description</Description>
<PrimaryCategory>
<CategoryID>377</CategoryID>
</PrimaryCategory>
<StartPrice>1.00</StartPrice>
<CategoryMappingAllowed>true</CategoryMappingAllowed>
<ConditionID>1000</ConditionID>
<Country>GB</Country>
<Currency>GBP</Currency>
<DispatchTimeMax>3</DispatchTimeMax>
<ListingDuration>Days_7</ListingDuration>
<ListingType>Chinese</ListingType>
<PaymentMethods>PayPal</PaymentMethods>
<PayPalEmailAddress>email#email.com</PayPalEmailAddress>
<PictureDetails>
<PictureURL>http://i1.sandbox.ebayimg.com/03/i/00/6b/63/03_1.JPG?set_id=8800005007 </PictureURL>
</PictureDetails>
<PostalCode>postcode</PostalCode>
<Quantity>1</Quantity>
<ShippingDetails>
<ShippingType>Flat</ShippingType>
<ShippingServiceOptions>
<ShippingServicePriority>1</ShippingServicePriority>
<ShippingService>UK_RoyalMailSecondClassRecorded</ShippingService>
<ShippingServiceCost>2.50</ShippingServiceCost>
</ShippingServiceOptions>
</ShippingDetails>
<Site>UK</Site>
</Item>
<RequesterCredentials>
<eBayAuthToken>Token String Here</eBayAuthToken>
</RequesterCredentials>
</VerifyAddItemRequest>
Error I receive:
Ebay Get Category
URL: https://api.ebay.com/ws/api.dll
Path to xml file: functions/tmp/Test.xml
content: 2015-08-15 21:00:07 100121SeriousError00RequestError 51SeriousError00RequestError 100111SeriousError00RequestError 100111SeriousError00RequestError 1115
Can anyone shed any light on where i am going wrong. If I can verify that the item will be successfully listed, I can go onto filling other details and list the item.
I am having trouble debugging this error i am recieving.
The "error" you see is the XML without the tags as the browser filters them. You have to look into the source (view source feature in your browser) or encode it properly or even parse it already as XML and obtain the error information from it (makes most sense as you're using an API).
Most likely important information about the error got lost that way. Most prominent still seems:
SeriousError00RequestError51
For which no concrete error information can be obtained in the vendors documentation about the error codes (which specifies nearly all error codes), which shows you already prevented yourself so far to give a clear picture of the error.
However most likely your problem is you have not understood that you need to pass XML as string to the service endpoint.
While you verify the file contains valid XML by using an XML parser (which is good!), you miss to pass the XML as string to the webservice:
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
As $xml is not a string but a SimpleXMLElement (which would effectively trigger $xml->__toString() which return text-content and not the whole XML) the correct form would be to use the SimpleXMLElement::asXML() method on it:
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml->asXML());
And that's it already.
The problem with your code is that you're loading in your XML file as a PHP Object rather than a string. Instead of using the simple_xml_loadfile function which returns an object, use file_get_contents to read the xml file into the $xml variable:
$xml = file_get_contents($xmlrequest);

Get data from XML sites

I want to get some data from a site based on xml's.
The problem is I need to be logged to it as a PublicUser without password.
I have tryed:
$url = 'http://IP/wcd/system_counter.xml';
$content = file_get_contents($url);
echo $content
But i only get this:
err En ReloginAttempt /wcd/index.html false
This is the xml code used for loggin:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="top.xsl" type="text/xsl"?>
<MFP>
<SelNo>Auto</SelNo>
<LangNo>En</LangNo>
<Service><Setting><AuthSetting><AuthMode><AuthType>None</AuthType>
<ListOn>false</ListOn>
<PublicUser>true</PublicUser>
<BoxAdmin>false</BoxAdmin>
</AuthMode><TrackMode><TrackType>None</TrackType></TrackMode></AuthSetting>
<MiddleServerSetting><ControlList><ArraySize>0</ArraySize></ControlList><Screen>
<Id>0</Id></Screen></MiddleServerSetting>
</Setting></Service><LangDummy>false</LangDummy></MFP>
Is there a way to send the user as well when i want to get the XML info ?
You cannot access pages requiring posted login information using file_get_contents. Instead you need to use curl. Something along these lines:
$ch = curl_init($url); // The url you want to call
curl_setopt_array(
$ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $login_xml, // The xml login in string form
)
);
//getting response from server
$response = curl_exec($ch);
echo curl_error($ch);
curl_close($ch);

simplexml_load_file($feedURL) returns bool(false) even that the RSS works

I am trying to make a simple widget that loads a youtube rss feed and shows the few first videos.
The problem is that even the RSS adress is correct it allways dumps false
$feedURL = 'http://gdata.youtube.com/feeds/api/users/ninpetit/uploads?alt=rss&v=2';
$sxml = simplexml_load_file($feedURL);
var_dump($sxml); /* output: bool(false) */
What am I doing wrong? Is there any alternative to simplexml_load_file?
PS: This code is being executed in a shared server
EDIT
I successfully getting the data vía curl, but the simplexml_load_file will return false if I pass the $data
$feedURL = 'http://gdata.youtube.com/feeds/api/users/ninpetit/uploads?alt=rss&v=2';
$ch = curl_init($feedURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
echo $data.'<br>'; /* shows data!! */
sxml = simplexml_load_file($data); /*Also false*/
if you have xml data in your $data string, you can easily parse it using simplexml_load_string() function.

Display xml data in a webpage with php

I am trying to display the data of a xml parsed page which i get from a external source. which i got passing through some parameters like this:-
http://www.somewebsite.com/phpfile.php?vendor_key=xxx&checkin=2012-11-02&checkout=2012-11-05&city_id=5&guests=3
when i pass this parameters i got an xml result. now i want to display that xml data in a designer way on my webpage. so how can i do so. i am new to xml so dont know what this technology called if any body can tell me what this called so that can also help me.
Take a look at simplexml_load_string.
You can use curl or file_get_contents function to make HTTP request. Then after you can use DOM or SimpleXML to parse the response (XML) of requested URL.
If u have already XMl then try
echo $xml->asXML();
A full example
<?php
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, 'http://rss.news.yahoo.com/rss/topstories');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($curl);
if ($result === false) {
die('Error fetching data: ' . curl_error($curl));
}
curl_close ($curl);
//we can at this point echo the XML if you want
//echo $result;
//parse xml string into SimpleXML objects
$xml = simplexml_load_string($result);
if ($xml === false) {
die('Error parsing XML');
}
//now we can loop through the xml structure
foreach ($xml->channel->item as $item) {
print $item->title;
}

PHP Regex for IP to Location API

How would I use Regex to get the information on a IP to Location API
This is the API
http://ipinfodb.com/ip_query.php?ip=74.125.45.100
I would need to get the Country Name, Region/State, and City.
I tried this:
$ip = $_SERVER["REMOTE_ADDR"];
$contents = #file_get_contents('http://ipinfodb.com/ip_query.php?ip=' . $ip . '');
$pattern = "/<CountryName>(.*)<CountryName>/";
preg_match($pattern, $contents, $regex);
$regex = !empty($regex[1]) ? $regex[1] : "FAIL";
echo $regex;
When I do echo $regex I always get FAIL how can I fix this
As Aaron has suggested. Best not to reinvent the wheel so try parsing it with simplexml_load_string()
// Init the CURL
$curl = curl_init();
// Setup the curl settings
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 0);
// grab the XML file
$raw_xml = curl_exec($curl);
curl_close($curl);
// Setup the xml object
$xml = simplexml_load_string( $raw_xml );
You can now access any part of the $xml variable as an object, with that in regard here is an example of what you posted.
<Response>
<Ip>74.125.45.100</Ip>
<Status>OK</Status>
<CountryCode>US</CountryCode>
<CountryName>United States</CountryName>
<RegionCode>06</RegionCode>
<RegionName>California</RegionName>
<City>Mountain View</City>
<ZipPostalCode>94043</ZipPostalCode>
<Latitude>37.4192</Latitude>
<Longitude>-122.057</Longitude>
<Timezone>0</Timezone>
<Gmtoffset>0</Gmtoffset>
<Dstoffset>0</Dstoffset>
</Response>
Now after you have loaded this XML string into the simplexml_load_string() you can access the response's IP address like so.
$xml->IP;
simplexml_load_string() will transform well formed XML files into an object that you can manipulate. The only other thing I can say is go and try it out and play with it
EDIT:
Source
http://www.php.net/manual/en/function.simplexml-load-string.php
You really are better off using a XML parser to pull the information.
For example, this script will parse it into an array.
Regex really shouldn't be used to parse HTML or XML.
If you really need to use regular expressions, then you should correct the one you are using. "|<CountryName>([^<]*)</CountryName>|i" would work better.

Categories