SimpleXML selecting attributes with PHP? - php

Okay so I've never worked with SimpleXML before and I'm having a few problems
Here's my PHP:
map.api.php
$location = $_SESSION['location'];
$address = $location; // Business Location
$prepAddr = str_replace(' ','+',$address);
$feedUrl="http://nominatim.openstreetmap.org/search?q=". $prepAddr ."&format=xml&addressdetails=1&polygon=1";
$sxml = simplexml_load_file($feedUrl);
foreach($sxml->attributes() as $type){
$lat = $type->place['lat'];
$long = $type->place['lon'];
}
And here's an example of the XML table I'm working from.
<searchresults timestamp="Thu, 28 Jan 16 14:16:34 +0000" attribution="Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright" querystring="M27 6bu, 149 Station road, Swinton, Manchester" polygon="true" exclude_place_ids="65827001" more_url="http://nominatim.openstreetmap.org/search.php?format=xml&exclude_place_ids=65827001&accept-language=en-US,en;q=0.8&polygon=1&addressdetails=1&q=M27+6bu%2C+149+Station+road%2C+Swinton%2C+Manchester">
<place place_id="65827001" osm_type="way" osm_id="32861649" place_rank="26" boundingbox="53.5122168,53.5190893,-2.3402445,-2.3331231" lat="53.5156919" lon="-2.3368185" display_name="Station Road, Newtown, Salford, Greater Manchester, North West England, England, M27 4AE, United Kingdom" class="highway" type="secondary" importance="0.5">
<road>Station Road</road>
<suburb>Newtown</suburb>
<town>Salford</town>
<county>Greater Manchester</county>
<state_district>North West England</state_district>
<state>England</state>
<postcode>M27 4AE</postcode>
<country>United Kingdom</country>
<country_code>gb</country_code>
</place>
</searchresults>
I want to select the "lat" and "lon" attributes from <place>, but when I echo $lat and $long they are empty, why?

When you call attributes as you did above, it's only going to act on the first element, which in your case is the root. You need to call attributes on the element you want the attributes for. Easiest way to do that would be
$sxml->place[0]->attributes()
Does that make sense? Basically you're telling SimpleXML to seek to the element you want to analyze, then returning a new SimpleXML object that represents that element's attributes. See if the docs help
Another option you have is using xpath to return all place elements, then iterating through those and calling attributes() on each element, in the case where you have more than one place.

Okay so I fixed this myself.
Instead of running everything through the foreach loop (as shown below):
foreach($sxml->attributes() as $type){
$lat = $type->place['lat'];
$long = $type->place['lon'];
}
I just directly got the attribute values and stored them in a variable:
$lat = $sxml->place->attributes()->lat;
$long = $sxml->place->attributes()->lon;
This then returned an error/warning: Warning: main() [function.main]: Node no longer exists
By using isset and checking if the value exists first, you can get around this.
if (isset($sxml->place))
{
$lat = $sxml->place->attributes()->lat;
$long = $sxml->place->attributes()->lon;
}

Related

PHP errors when trying to apply geo location

I'm trying to do some geolocating to display certain phone numbers in the header of my WordPress website. Unfortunately when I apply the code below i get the following PHP error:
[17-Sep-2014 19:48:16 UTC] PHP Warning: strpos() [function.strpos]: Empty needle in /home/domain/public_html/wp-content/themes/Avada/framework/headers/header-v4.php on line 87
[17-Sep-2014 19:48:16 UTC] PHP Warning: strpos() [function.strpos]: Empty needle in /home/domain/public_html/wp-content/themes/Avada/framework/headers/header-v4.php on line 90
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$url = "http://freegeoip.net/json/" . $ip;
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
$city = print_r($data['city'], true);
$state = print_r($data['region_code'], true);
$kings_orlando = "Altamonte Springs Apopka Casselberry College Park Heathrow Lake Mary Longwood Maitland Orlando Oviedo Windermere Winter Park Winter Springs";
if ((strpos($kings_orlando,$city) !== false) AND ($state == "FL")) {
echo '1-407-270-2112';
}
else {
echo '1-954-753-9436';
}
?>
Not only do I get the error but my footer disappears as well. Can someone tell me what i'm doing wrong?
Thanks in advance
I'm taking a guess here: You're trying this locally. Hence, your IP address is 127.0.0.1.
For this IP freegeoip.net – obviously – doesn't know a city. You can see this by just looking at the output: https://freegeoip.net/json/127.0.0.1
So you have to expect that $city is simply empty. Catch this problem by doing this:
if (!empty($city) AND (strpos($kings_orlando,$city) !== false) AND ($state == "FL")) {
(Of course, this can also happen with "real" IP addresses – the GeoLite database that freegeoip.net is using is far from complete, especially on a city level.)
Firstly, using this freegeoip.net service is wrong :) (as long as you need it for more than just a country). It's highly inaccurate and often unavailable, but maybe it's just me who had a lot of problems with it even in a small startup-website.
Secondly - using $city = print_r($data['city'], true); is wrong.
You should only do $city = $data['city']; if even that.
Those warnings you get mean that $city variable is empty, which is very possible (see: point 1. of my answer ;). Try other geolocating services or make sure you handle situations, where city is not provided in returned JSON.

PHP simplexml and xpath to access node values

I have the below XML response from the UPS Rates API and I need to get the values of 'ServiceType', 'Amount' and 'Currency' nodes for each 'RateReplyDetails' only where the RateType node = 'RATED_ACCOUNT_SHIPMENT' .
My attempt is below, the ServiceType works but not the amount and currency. Can anyone assist?
$RateReply = $fedex_xml->children("env", true)->Body->children("v13", true)->RateReply;
foreach($RateReply->RateReplyDetails as $details){
$service = $details->ServiceType;
$amount = $details->xpath("/RatedShipmentDetails/ShipmentRateDetail/RateType['RATED_ACCOUNT_SHIPMENT']/TotalNetCharge/Amount");
$currency = $details->xpath("/RatedShipmentDetails/ShipmentRateDetail/RateType['RATED_ACCOUNT_SHIPMENT']/TotalNetCharge/Currency");
}
<soapenv:Envelope><env:Header/><env:Body><v13:RateReply><v13:HighestSeverity>SUCCESS</v13:HighestSeverity><v13:Notifications><v13:Severity>SUCCESS</v13:Severity><v13:Source>crs</v13:Source><v13:Code>0</v13:Code><v13:Message>Request was successfully processed. </v13:Message><v13:LocalizedMessage>Request was successfully processed. </v13:LocalizedMessage></v13:Notifications><ns1:TransactionDetail><ns1:CustomerTransactionId> *** Rate Available Services Request v13 using PHP ***</ns1:CustomerTransactionId></ns1:TransactionDetail><ns1:Version><ns1:ServiceId>crs</ns1:ServiceId><ns1:Major>13</ns1:Major><ns1:Intermediate>0</ns1:Intermediate><ns1:Minor>0</ns1:Minor></ns1:Version><v13:RateReplyDetails><v13:ServiceType>INTERNATIONAL_FIRST</v13:ServiceType><v13:PackagingType>YOUR_PACKAGING</v13:PackagingType><v13:DeliveryStation>DKKA </v13:DeliveryStation><v13:DeliveryDayOfWeek>THU</v13:DeliveryDayOfWeek><v13:DeliveryTimestamp>2012-12-13T09:00:00</v13:DeliveryTimestamp><v13:CommitDetails><v13:CommodityName>DOCUMENTS</v13:CommodityName><v13:ServiceType>INTERNATIONAL_FIRST</v13:ServiceType><v13:CommitTimestamp>2012-12-13T09:00:00</v13:CommitTimestamp><v13:DayOfWeek>THU</v13:DayOfWeek><v13:DestinationServiceArea>A4</v13:DestinationServiceArea><v13:BrokerToDestinationDays>0</v13:BrokerToDestinationDays><v13:CommitMessages><v13:Code>134</v13:Code><v13:Message>REQUEST COMPLETED</v13:Message></v13:CommitMessages><v13:DeliveryMessages> 9:00 A.M. IF NO CUSTOMS DELAY</v13:DeliveryMessages><v13:DocumentContent>DOCUMENTS_ONLY</v13:DocumentContent><v13:RequiredDocuments>INTERNATIONAL_AIRWAY_BILL</v13:RequiredDocuments></v13:CommitDetails><v13:DestinationAirportId>BUF</v13:DestinationAirportId><v13:IneligibleForMoneyBackGuarantee>false</v13:IneligibleForMoneyBackGuarantee><v13:OriginServiceArea>AM</v13:OriginServiceArea><v13:DestinationServiceArea>A4</v13:DestinationServiceArea><v13:SignatureOption>INDIRECT</v13:SignatureOption><v13:ActualRateType>PAYOR_ACCOUNT_SHIPMENT</v13:ActualRateType><v13:RatedShipmentDetails><v13:ShipmentRateDetail><v13:RateType>PAYOR_ACCOUNT_SHIPMENT</v13:RateType><v13:RateScale>0000000</v13:RateScale><v13:RateZone>GB001O</v13:RateZone><v13:PricingCode>ACTUAL</v13:PricingCode><v13:RatedWeightMethod>ACTUAL</v13:RatedWeightMethod><v13:CurrencyExchangeRate><v13:FromCurrency>UKL</v13:FromCurrency><v13:IntoCurrency>USD</v13:IntoCurrency><v13:Rate>1.59</v13:Rate></v13:CurrencyExchangeRate><v13:DimDivisor>0</v13:DimDivisor><v13:FuelSurchargePercent>17.5</v13:FuelSurchargePercent><v13:TotalBillingWeight><v13:Units>KG</v13:Units><v13:Value>1.0</v13:Value></v13:TotalBillingWeight><v13:TotalBaseCharge><v13:Currency>USD</v13:Currency><v13:Amount>129.74</v13:Amount></v13:TotalBaseCharge><v13:TotalFreightDiscounts><v13:Currency>USD</v13:Currency><v13:Amount>0.0</v13:Amount></v13:TotalFreightDiscounts><v13:TotalNetFreight><v13:Currency>USD</v13:Currency><v13:Amount>129.74</v13:Amount></v13:TotalNetFreight><v13:TotalSurcharges><v13:Currency>USD</v13:Currency><v13:Amount>22.71</v13:Amount></v13:TotalSurcharges><v13:TotalNetFedExCharge><v13:Currency>USD</v13:Currency><v13:Amount>152.45</v13:Amount></v13:TotalNetFedExCharge><v13:TotalTaxes><v13:Currency>USD</v13:Currency><v13:Amount>0.0</v13:Amount></v13:TotalTaxes><v13:TotalNetCharge><v13:Currency>USD</v13:Currency><v13:Amount>152.45</v13:Amount></v13:TotalNetCharge><v13:TotalRebates><v13:Currency>USD</v13:Currency><v13:Amount>0.0</v13:Amount></v13:TotalRebates><v13:Surcharges><v13:SurchargeType>FUEL</v13:SurchargeType><v13:Description>Fuel</v13:Description><v13:Amount><v13:Currency>USD</v13:Currency><v13:Amount>22.71</v13:Amount></v13:Amount></v13:Surcharges></v13:ShipmentRateDetail></v13:RatedShipmentDetails><v13:RatedShipmentDetails><v13:ShipmentRateDetail><v13:RateType>RATED_ACCOUNT_SHIPMENT</v13:RateType><v13:RateScale>0000000</v13:RateScale><v13:RateZone>GB001O</v13:RateZone><v13:PricingCode>ACTUAL</v13:PricingCode><v13:RatedWeightMethod>ACTUAL</v13:RatedWeightMethod><v13:CurrencyExchangeRate><v13:FromCurrency>UKL</v13:FromCurrency><v13:IntoCurrency>UKL</v13:IntoCurrency><v13:Rate>1.0</v13:Rate></v13:CurrencyExchangeRate><v13:DimDivisor>0</v13:DimDivisor><v13:FuelSurchargePercent>17.5</v13:FuelSurchargePercent><v13:TotalBillingWeight><v13:Units>KG</v13:Units><v13:Value>1.0</v13:Value></v13:TotalBillingWeight><v13:TotalBaseCharge><v13:Currency>UKL</v13:Currency><v13:Amount>81.7</v13:Amount></v13:TotalBaseCharge><v13:TotalFreightDiscounts><v13:Currency>UKL</v13:Currency><v13:Amount>0.0</v13:Amount></v13:TotalFreightDiscounts><v13:TotalNetFreight><v13:Currency>UKL</v13:Currency><v13:Amount>81.7</v13:Amount></v13:TotalNetFreight><v13:TotalSurcharges><v13:Currency>UKL</v13:Currency><v13:Amount>14.3</v13:Amount></v13:TotalSurcharges><v13:TotalNetFedExCharge><v13:Currency>UKL</v13:Currency><v13:Amount>96.0</v13:Amount></v13:TotalNetFedExCharge><v13:TotalTaxes><v13:Currency>UKL</v13:Currency><v13:Amount>0.0</v13:Amount></v13:TotalTaxes><v13:TotalNetCharge><v13:Currency>UKL</v13:Currency><v13:Amount>96.0</v13:Amount></v13:TotalNetCharge><v13:TotalRebates><v13:Currency>UKL</v13:Currency><v13:Amount>0.0</v13:Amount></v13:TotalRebates><v13:Surcharges><v13:SurchargeType>FUEL</v13:SurchargeType><v13:Description>Fuel</v13:Description><v13:Amount><v13:Currency>UKL</v13:Currency><v13:Amount>14.3</v13:Amount></v13:Amount></v13:Surcharges></v13:ShipmentRateDetail></v13:RatedShipmentDetails></v13:RateReplyDetails><v13:RateReplyDetails><v13:ServiceType>INTERNATIONAL_PRIORITY</v13:ServiceType><v13:PackagingType>YOUR_PACKAGING</v13:PackagingType><v13:DeliveryStation>DKKA </v13:DeliveryStation><v13:DeliveryDayOfWeek>THU</v13:DeliveryDayOfWeek><v13:DeliveryTimestamp>2012-12-13T10:30:00</v13:DeliveryTimestamp><v13:CommitDetails><v13:CommodityName>DOCUMENTS</v13:CommodityName><v13:ServiceType>INTERNATIONAL_PRIORITY</v13:ServiceType><v13:CommitTimestamp>2012-12-13T10:30:00</v13:CommitTimestamp><v13:DayOfWeek>THU</v13:DayOfWeek><v13:DestinationServiceArea>A4</v13:DestinationServiceArea><v13:BrokerToDestinationDays>0</v13:BrokerToDestinationDays><v13:CommitMessages><v13:Code>134</v13:Code><v13:Message>REQUEST COMPLETED</v13:Message></v13:CommitMessages><v13:DeliveryMessages>10:30 A.M. IF NO CUSTOMS DELAY</v13:DeliveryMessages><v13:DocumentContent>DOCUMENTS_ONLY</v13:DocumentContent><v13:RequiredDocuments>INTERNATIONAL_AIRWAY_BILL</v13:RequiredDocuments></v13:CommitDetails><v13:DestinationAirportId>BUF</v13:DestinationAirportId><v13:IneligibleForMoneyBackGuarantee>false</v13:IneligibleForMoneyBackGuarantee><v13:OriginServiceArea>AM</v13:OriginServiceArea><v13:DestinationServiceArea>A4</v13:DestinationServiceArea><v13:SignatureOption>INDIRECT</v13:SignatureOption><v13:ActualRateType>PAYOR_ACCOUNT_SHIPMENT</v13:ActualRateType><v13:RatedShipmentDetails><v13:ShipmentRateDetail><v13:RateType>PAYOR_ACCOUNT_SHIPMENT</v13:RateType><v13:RateScale>0000000</v13:RateScale><v13:RateZone>GB001O</v13:RateZone><v13:PricingCode>ACTUAL</v13:PricingCode><v13:RatedWeightMethod>ACTUAL</v13:RatedWeightMethod><v13:CurrencyExchangeRate><v13:FromCurrency>UKL</v13:FromCurrency><v13:IntoCurrency>USD</v13:IntoCurrency><v13:Rate>1.59</v13:Rate></v13:CurrencyExchangeRate><v13:DimDivisor>0</v13:DimDivisor><v13:FuelSurchargePercent>17.5</v13:FuelSurchargePercent><v13:TotalBillingWeight><v13:Units>KG</v13:Units><v13:Value>1.0</v13:Value></v13:TotalBillingWeight><v13:TotalBaseCharge><v13:Currency>USD</v13:Currency><v13:Amount>98.46</v13:Amount></v13:TotalBaseCharge><v13:TotalFreightDiscounts><v13:Currency>USD</v13:Currency><v13:Amount>0.0</v13:Amount></v13:TotalFreightDiscounts><v13:TotalNetFreight><v13:Currency>USD</v13:Currency><v13:Amount>98.46</v13:Amount></v13:TotalNetFreight><v13:TotalSurcharges><v13:Currency>USD</v13:Currency><v13:Amount>17.23</v13:Amount></v13:TotalSurcharges><v13:TotalNetFedExCharge><v13:Currency>USD</v13:Currency><v13:Amount>115.69</v13:Amount></v13:TotalNetFedExCharge><v13:TotalTaxes><v13:Currency>USD</v13:Currency><v13:Amount>0.0</v13:Amount></v13:TotalTaxes><v13:TotalNetCharge><v13:Currency>USD</v13:Currency><v13:Amount>115.69</v13:Amount></v13:TotalNetCharge><v13:TotalRebates><v13:Currency>USD</v13:Currency><v13:Amount>0.0</v13:Amount></v13:TotalRebates><v13:Surcharges><v13:SurchargeType>FUEL</v13:SurchargeType><v13:Description>Fuel</v13:Description><v13:Amount><v13:Currency>USD</v13:Currency><v13:Amount>17.23</v13:Amount></v13:Amount></v13:Surcharges></v13:ShipmentRateDetail></v13:RatedShipmentDetails><v13:RatedShipmentDetails><v13:ShipmentRateDetail><v13:RateType>RATED_ACCOUNT_SHIPMENT</v13:RateType><v13:RateScale>0000000</v13:RateScale><v13:RateZone>GB001O</v13:RateZone><v13:PricingCode>ACTUAL</v13:PricingCode><v13:RatedWeightMethod>ACTUAL</v13:RatedWeightMethod><v13:CurrencyExchangeRate><v13:FromCurrency>UKL</v13:FromCurrency><v13:IntoCurrency>UKL</v13:IntoCurrency><v13:Rate>1.0</v13:Rate></v13:CurrencyExchangeRate><v13:DimDivisor>0</v13:DimDivisor><v13:FuelSurchargePercent>17.5</v13:FuelSurchargePercent><v13:TotalBillingWeight><v13:Units>KG</v13:Units><v13:Value>1.0</v13:Value></v13:TotalBillingWeight><v13:TotalBaseCharge><v13:Currency>UKL</v13:Currency><v13:Amount>62.0</v13:Amount></v13:TotalBaseCharge><v13:TotalFreightDiscounts><v13:Currency>UKL</v13:Currency><v13:Amount>0.0</v13:Amount></v13:TotalFreightDiscounts><v13:TotalNetFreight><v13:Currency>UKL</v13:Currency><v13:Amount>62.0</v13:Amount></v13:TotalNetFreight><v13:TotalSurcharges><v13:Currency>UKL</v13:Currency><v13:Amount>10.85</v13:Amount></v13:TotalSurcharges><v13:TotalNetFedExCharge><v13:Currency>UKL</v13:Currency><v13:Amount>72.85</v13:Amount></v13:TotalNetFedExCharge><v13:TotalTaxes><v13:Currency>UKL</v13:Currency><v13:Amount>0.0</v13:Amount></v13:TotalTaxes><v13:TotalNetCharge><v13:Currency>UKL</v13:Currency><v13:Amount>72.85</v13:Amount></v13:TotalNetCharge><v13:TotalRebates><v13:Currency>UKL</v13:Currency><v13:Amount>0.0</v13:Amount></v13:TotalRebates><v13:Surcharges><v13:SurchargeType>FUEL</v13:SurchargeType><v13:Description>Fuel</v13:Description><v13:Amount><v13:Currency>UKL</v13:Currency><v13:Amount>10.85</v13:Amount></v13:Amount></v13:Surcharges></v13:ShipmentRateDetail></v13:RatedShipmentDetails></v13:RateReplyDetails><v13:RateReplyDetails><v13:ServiceType>INTERNATIONAL_ECONOMY</v13:ServiceType><v13:PackagingType>YOUR_PACKAGING</v13:PackagingType><v13:DeliveryStation>DKKA </v13:DeliveryStation><v13:DeliveryDayOfWeek>MON</v13:DeliveryDayOfWeek><v13:DeliveryTimestamp>2012-12-17T16:30:00</v13:DeliveryTimestamp><v13:CommitDetails><v13:CommodityName>DOCUMENTS</v13:CommodityName><v13:ServiceType>INTERNATIONAL_ECONOMY</v13:ServiceType><v13:CommitTimestamp>2012-12-17T16:30:00</v13:CommitTimestamp><v13:DayOfWeek>MON</v13:DayOfWeek><v13:DestinationServiceArea>A4</v13:DestinationServiceArea><v13:BrokerToDestinationDays>0</v13:BrokerToDestinationDays><v13:CommitMessages><v13:Code>134</v13:Code><v13:Message>REQUEST COMPLETED</v13:Message></v13:CommitMessages><v13:DeliveryMessages> 4:30 P.M. IF NO CUSTOMS DELAY</v13:DeliveryMessages><v13:DocumentContent>DOCUMENTS_ONLY</v13:DocumentContent><v13:RequiredDocuments>INTERNATIONAL_AIRWAY_BILL</v13:RequiredDocuments></v13:CommitDetails><v13:DestinationAirportId>BUF</v13:DestinationAirportId><v13:IneligibleForMoneyBackGuarantee>false</v13:IneligibleForMoneyBackGuarantee><v13:OriginServiceArea>AM</v13:OriginServiceArea><v13:DestinationServiceArea>A4</v13:DestinationServiceArea><v13:SignatureOption>INDIRECT</v13:SignatureOption><v13:ActualRateType>PAYOR_ACCOUNT_SHIPMENT</v13:ActualRateType><v13:RatedShipmentDetails></v13:RatedShipmentDetails><v13:RatedShipmentDetails><v13:ShipmentRateDetail><v13:RateType>RATED_ACCOUNT_SHIPMENT</v13:RateType><v13:RateScale>0000000</v13:RateScale><v13:RateZone>GB001O</v13:RateZone><v13:PricingCode>ACTUAL</v13:PricingCode><v13:RatedWeightMethod>ACTUAL</v13:RatedWeightMethod><v13:CurrencyExchangeRate><v13:FromCurrency>UKL</v13:FromCurrency><v13:IntoCurrency>UKL</v13:IntoCurrency><v13:Rate>1.0</v13:Rate></v13:CurrencyExchangeRate><v13:DimDivisor>0</v13:DimDivisor><v13:FuelSurchargePercent>17.5</v13:FuelSurchargePercent><v13:TotalBillingWeight><v13:Units>KG</v13:Units><v13:Value>1.0</v13:Value></v13:TotalBillingWeight><v13:TotalBaseCharge><v13:Currency>UKL</v13:Currency><v13:Amount>49.7</v13:Amount></v13:TotalBaseCharge><v13:TotalFreightDiscounts><v13:Currency>UKL</v13:Currency><v13:Amount>0.0</v13:Amount></v13:TotalFreightDiscounts><v13:TotalNetFreight><v13:Currency>UKL</v13:Currency><v13:Amount>49.7</v13:Amount></v13:TotalNetFreight><v13:TotalSurcharges><v13:Currency>UKL</v13:Currency><v13:Amount>8.7</v13:Amount></v13:TotalSurcharges><v13:TotalNetFedExCharge><v13:Currency>UKL</v13:Currency><v13:Amount>58.4</v13:Amount></v13:TotalNetFedExCharge><v13:TotalTaxes><v13:Currency>UKL</v13:Currency><v13:Amount>0.0</v13:Amount></v13:TotalTaxes><v13:TotalNetCharge><v13:Currency>UKL</v13:Currency><v13:Amount>58.4</v13:Amount></v13:TotalNetCharge><v13:TotalRebates><v13:Currency>UKL</v13:Currency><v13:Amount>0.0</v13:Amount></v13:TotalRebates><v13:Surcharges><v13:SurchargeType>FUEL</v13:SurchargeType><v13:Description>Fuel</v13:Description><v13:Amount><v13:Currency>UKL</v13:Currency><v13:Amount>8.7</v13:Amount></v13:Amount></v13:Surcharges></v13:ShipmentRateDetail></v13:RatedShipmentDetails></v13:RateReplyDetails></v13:RateReply></env:Body></soapenv:Envelope>
//amount
"/RatedShipmentDetails/ShipmentRateDetail[RateType = 'RATED_ACCOUNT_SHIPMENT']/TotalNetCharge/Amount"
//currency
"/RatedShipmentDetails/ShipmentRateDetail[RateType = 'RATED_ACCOUNT_SHIPMENT']/TotalNetCharge/Currency"
see them running here
sources for xpath: doc examples
Update
foreach ($fedex_xml->xpath("//RateReply//RateReplyDetails") as $details) {
$amounts = $details->xpath("./RatedShipmentDetails/ShipmentRateDetail[RateType = 'RATED_ACCOUNT_SHIPMENT']/TotalNetCharge/Amount");
$currencies = $details->xpath("./RatedShipmentDetails/ShipmentRateDetail[RateType = 'RATED_ACCOUNT_SHIPMENT']/TotalNetCharge/Currency");
var_dump($amounts);
var_dump($currencies);
}
I used a xpath expression to select every RateReplyDetails, then used some other xpath expressions to extract the values. Note that the ./ part at the beginning of these are very important, it says interpret the xpath expression in the current scope (RateReplyDetails node).

Put XML string (node value) in server text file and retrieve and echo it again (PHP)

This is my problem. I'm trying to retrieve a value from an XML url (from last.fm api). For example the biography of an artist.
I already know that I can do it simply like this (e.g. for Adele):
<?php
$xml = simplexml_load_file("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=adele&api_key=b25b959554ed76058ac220b7b2e0a026");
$info = $xml->artist->bio->summary;
echo $info;
?>
This returns:
Adele Laurie Blue Adkins, (born 5 May 1988), is a Grammy Award-Winning English singer-songwriter from Enfield, North London. Her debut album, <a title="Adele - 19" href="http://www.last.fm/music/Adele/19" class="bbcode_album">19</a>, was released in January 2008 and entered the UK album chart at #1. The album has since received four-times Platinum certification in the UK and has sold 5,500,000 copies worldwide. The album included the hugely popular song <a title="Adele – Chasing Pavements" href="http://www.last.fm/music/Adele/_/Chasing+Pavements" class="bbcode_track">Chasing Pavements</a>. 19 earned Adele two Grammy Awards in February 2009 for Best New Artist and Best Female Pop Vocal Performance.
I would now like to put that result in a text file and store it on a folder on my website, for example: "http://mysite.com/artistdescriptions/adele.txt".
I've already tried:
<?php
$file_path = $_SERVER['DOCUMENT_ROOT'].'/artistdescriptions/adele.txt';
$xml = simplexml_load_file("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=adele&api_key=b25b959554ed76058ac220b7b2e0a026");
$info = $xml->artist->bio->summary;
file_put_contents($file_path, serialize($info));
$file_contents = file_get_contents($file_path);
if(!empty($file_contents)) {
$data = unserialize($file_contents);
echo $data;
}
?>
But this unfortunately didn't work. Any help would be greatly appreciated!
Echo call magic method __toString(), but serialize doesn't, and in SimpleXMLElement isn't serialize allowed, so it throw an Exception. But you can call __toString() magic method by yourself, and this solve you problem.
Replace your line with mine
$info = $xml->artist->bio->summary->__toString();

Map cities of UK onto postcodes

I was wondering if anyone is aware of any PHP scripts which maps a UK City onto a Post Code.
I have found something like this:
case'North West England, England': {
$postcode = 'M1 2NQ';
break;
}
case'North East England, England': {
$postcode = 'NE1 6AD';
break;
}
case'South West England, England': {
$postcode = 'EX1 3AX';
break;
}
But it only covers areas as you can see, rather than cities such as 'Manchester, Edinburgh' etc.
Any input would be greatly appreciated.
Thanks,
AP
You might think of using Google Map API
You can use the ONS Postcode Directory (ONSPD). You'd have to set up a database and import all the data, then build your application round it.

PHP & API for IP Geolocation

I am trying to use http://www.hostip.info/use.html in my web app to show the approximate City location of an IP address. I cannot figure out how to actually show the contents of the API... Here is what I have that is not working.
function showCity($currIP){
$lookupData = 'http://api.hostip.info/get_html.php?ip='.$currIP;
return $lookupData;
}
Your API returns this:
Country: UNITED STATES (US)
City: Seattle, WA
IP: 168.111.127.225
So you need to do some string parsing on that result. Using the below will get your started:
$array = preg_split('/$\R?^:/m', $lookupData);
print_r($array);
Try this instead:
$array = preg_split("/[\r\n]/", $lookupData, -1, PREG_SPLIT_NO_EMPTY);
Also, as was mentioned by mcmajkel, if you use the JSON api link, you can get to it with this:
$lookupData = 'http://api.hostip.info/get_json.php?ip='.$currIP;
$api = json_decode($lookupData);
$myName = $api->country_name;
$myCode = $api->country_code;
$myCity = $api->city;
$myIP = $api->ip;
This call returns string, as mentioned by GregP. But you can call
http://api.hostip.info/get_json.php?ip=12.215.42.19
And get a nice piece of JSON in return, which will be easier to
parse

Categories