PHP simplexml and xpath to access node values - php

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).

Related

SimpleXML selecting attributes with 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;
}

Php-ews: creating contact birthday's event

I am trying to add a contact in Exchange, using the php-ews and the following code:
$request = new EWSType_CreateItemType();
$request->SendMeetingInvitations = 'SendToNone';
$contact = new EWSType_ContactItemType();
$contact->GivenName = $updates['name'];
$contact->Surname = $updates['surname'];
if($updates['email'] != ""){
$email = new EWSType_EmailAddressDictionaryEntryType();
$email->Key = new EWSType_EmailAddressKeyType();
$email->Key->_ = EWSType_EmailAddressKeyType::EMAIL_ADDRESS_1;
$email->_ = $updates['email'];
// set the email
$contact->EmailAddresses = new EWSType_EmailAddressDictionaryType();
$contact->EmailAddresses->Entry[] = $email;
}
$contact->CompanyName = $updates['companyname'];
$contact->JobTitle = $updates['jobtitle'];
$contact->Birthday = $updates['birthday'];
$request->Items->Contact[] = $contact;
$response = $this->ews->CreateItem($request);
Where $updates is an array of strings I have as a parameter.
(I skipped the includes, tell me if you need them.)
Now, the contact gets created and everything works, but the birthday event does not get created automatically in my calendar.
So, I would like to know if there's a simple way to have this done, except the obvious (non-elegant) way of creating it manually.
Thank you in advance,
Riccardo
Could solve this using DateTime in the right format as expected in the comments.
$contact->Birthday = (new DateTime($updates['birthday']))->format(DATE_W3C);
https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/time-zones-and-ews-in-exchange
The time zone specified in the value of dateTime elements can take three forms. You can read all the details in XML Schema Part 2: Datatypes Second Edition, but to paraphrase:
Universal Coordinated Time (UTC): Specified by 'Z'. For example, 2014-06-06T19:00:00.000Z
Specific time zone: Specified by '+' or '-' followed by hours and minutes. For example, 2014-06-06T19:00:00.000-08:00
No time zone: Specified by the absence of any time zone. For example, 2014-06-06T19:00:00.000

How do I set the SalesTerm for a Customer with QuickBooks_IPP?

I'm successfully adding a Customer to QuickBooks using QuickBooks_IPP, but I'm having difficulty setting the sales term for the customer. I've looked through the documentation and cannot find examples of setting the SalesTerm.
I've added these lines to the example code, but does not throw an error and does not add the sales term.
$Term = new QuickBooks_IPP_Object_SalesTerm();
$Term->setSalesTermRef(2); //15 days
$Customer->setSalesTermRef($Term);
This is the full Customer add code:
// Set the IPP version to v3
$IPP->version(QuickBooks_IPP_IDS::VERSION_3);
$CustomerService = new QuickBooks_IPP_Service_Customer();
$Customer = new QuickBooks_IPP_Object_Customer();
$Customer->setTitle('Ms');
$Customer->setGivenName('Shannon');
$Customer->setMiddleName('B');
$Customer->setFamilyName('Palmer');
$Customer->setDisplayName('Shannon B Palmer ' . mt_rand(0, 1000));
//set days due
$Term = new QuickBooks_IPP_Object_SalesTerm();
$Term->setSalesTermRef(2);
$Customer->setSalesTermRef($Term);
// Phone #
$PrimaryPhone = new QuickBooks_IPP_Object_PrimaryPhone();
$PrimaryPhone->setFreeFormNumber('860-532-0089');
$Customer->setPrimaryPhone($PrimaryPhone);
// Mobile #
$Mobile = new QuickBooks_IPP_Object_Mobile();
$Mobile->setFreeFormNumber('860-532-0089');
$Customer->setMobile($Mobile);
// Fax #
$Fax = new QuickBooks_IPP_Object_Fax();
$Fax->setFreeFormNumber('860-532-0089');
$Customer->setFax($Fax);
// Bill address
$BillAddr = new QuickBooks_IPP_Object_BillAddr();
$BillAddr->setLine1('72 E Blue Grass Road');
$BillAddr->setLine2('Suite D');
$BillAddr->setCity('Mt Pleasant');
$BillAddr->setCountrySubDivisionCode('MI');
$BillAddr->setPostalCode('48858');
$Customer->setBillAddr($BillAddr);
// Email
$PrimaryEmailAddr = new QuickBooks_IPP_Object_PrimaryEmailAddr();
$PrimaryEmailAddr->setAddress('support#consolibyte.com');
$Customer->setPrimaryEmailAddr($PrimaryEmailAddr);
if ($resp = $CustomerService->add($Context, $realm, $Customer))
{
print('Our new customer ID is: [' . $resp . ']');
}
else
{
print($CustomerService->lastError($Context));
}
I can query for the Customer after the add but it does not return the SalesTerm as I would expect. Do I need the SalesTerm Service instead of the Object?
The only time you'd wrap something in an object like you're doing with QuickBooks_IPP_Object_SalesTerm is if it's actually a full nested node in the XML request.
i.e. if you saw this in Intuit's documentation:
<Customer>
...
<SalesTermRef>
<Id>...</Id>
... other nested tags inside here ...
</SalesTermRef>
...
</Customer>
Then you would have been on the right track.
But per Intuit's docs, this is only a normal non-nested node:
<SalesTermRef>4</SalesTermRef>
So just use the ->setSalesTermRef($val) method:
// Terms (e.g. Net 30, etc.)
$Customer->setSalesTermRef(4);
Sometimes the easiest way to see this stuff is to examine the XML output. Look at what you're sending with:
print($CustomerService->lastRequest());

How do I submit an address to Paypal Express Checkout?

I'm in the process of writing some code that will submit an order to Paypal Express Checkout. Unforunately I can't seem to get the whole address thing to work, and I also can't seem to find much info on it in the API docs. Here's my code so far.
$config = array (
'mode' => 'sandbox' ,
'acct1.UserName' => '****removed*****',
'acct1.Password' => '******removed*******',
'acct1.Signature' => '*********removed***********'
);
$paypalService = new PayPal\Service\PayPalAPIInterfaceServiceService($config);
$paymentDetails= new PayPal\EBLBaseComponents\PaymentDetailsType();
// Dummy shipping address
// Obviously, in the final version, this would be passed in from a form
$shipping_address = new PayPal\EBLBaseComponents\AddressType();
$shipping_address->Name = "John Smith";
$shipping_address->Street1 = "123 Market Street";
$shipping_address->Street2 = "";
$shipping_address->CityName = "Columbus";
$shipping_address->StateOrProvince = "OH";
$shipping_address->PostalCode = "43017";
$shipping_address->Country = "US";
// A dummy item
// Once again, in a final version this would be passed in
$itemDetails = new PayPal\EBLBaseComponents\PaymentDetailsItemType();
$itemDetails->Name = 'Electro Lettuce Feeders';
$itemAmount = 1250.00;
$itemDetails->Amount = $itemAmount;
$itemQuantity = 1;
$itemDetails->Quantity = $itemQuantity;
// Add all items to the list
$paymentDetails->PaymentDetailsItem[0] = $itemDetails;
// The company is in NYS, so in the final version the
// sales tax rate will be passed in (NYS is destination-based)
$sales_tax_rate = 0.07;
// Order sub-total
$itemTotal = new PayPal\CoreComponentTypes\BasicAmountType();
$itemTotal->currencyID = 'USD';
$itemTotal->value = ($itemAmount * $itemQuantity);
// Shipping total
$shippingTotal = new PayPal\CoreComponentTypes\BasicAmountType();
$shippingTotal->currencyID = 'USD';
$shippingTotal->value = 2.00;
// Tax total
$taxTotal = new PayPal\CoreComponentTypes\BasicAmountType();
$taxTotal->currencyID = 'USD';
$taxTotal->value = $itemTotal->value * $sales_tax_rate;
// Order total
$orderTotal = new PayPal\CoreComponentTypes\BasicAmountType();
$orderTotal->currencyID = 'USD';
$orderTotal->value = $itemTotal->value + $taxTotal->value + $shippingTotal->value;
$paymentDetails->TaxTotal = $taxTotal;
$paymentDetails->ItemTotal = $itemTotal;
$paymentDetails->ShippingTotal = $shippingTotal;
$paymentDetails->OrderTotal = $orderTotal;
$paymentDetails->PaymentAction = 'Sale';
// ***** Is the address from this object passed to Paypal?
$paymentDetails->ShipToAddress = $shipping_address;
$setECReqDetails = new PayPal\EBLBaseComponents\SetExpressCheckoutRequestDetailsType();
$setECReqDetails->PaymentDetails[0] = $paymentDetails;
$setECReqDetails->CancelURL = 'https://devtools-paypal.com/guide/expresscheckout/php?cancel=true';
$setECReqDetails->ReturnURL = 'https://devtools-paypal.com/guide/expresscheckout/php?success=true';
// ***** Or is this the address that will be passed to Paypal?
$setECReqDetails->Address = $shipping_address;
// ***** And can you choose to not pass in the billing address? Or is it required? *****
$setECReqDetails->BillingAddress = $shipping_address;
// ***** If this is set to 0, will the previously provided shipping address be shown
// ***** at all? Or will it just be "modify-able" unless you set this to 1?
$setECReqDetails->AddressOverride = 1;
$setECReqType = new PayPal\PayPalAPI\SetExpressCheckoutRequestType();
$setECReqType->Version = '104.0';
$setECReqType->SetExpressCheckoutRequestDetails = $setECReqDetails;
$setECReq = new PayPal\PayPalAPI\SetExpressCheckoutReq();
$setECReq->SetExpressCheckoutRequest = $setECReqType;
$setECResponse = $paypalService->SetExpressCheckout($setECReq);
//var_dump($setECResponse);
$redirect_url = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=".$setECResponse->Token;
return $app->redirect($redirect_url);
Summed up...
You'll see my questions distributed throughout the code, but here they are all summed up.
Both PaymentDetailsType() and SetExpressCheckoutRequestType() have address-ish properties. Which one will be passed on to Paypal?
Does the API require that you pass in a billing address if you pass in a shipping address?
If you don't set AddressOverride to 1, should it show the address that you passed in at all?
But in the end, I most importantly just want to know how to get address passing to work. =). Right now I can't seem to get any address to pass to Paypal no matter what I try.
It would help more to see the raw API requests getting generated as opposed to the code generating the requests. The library you're using should give you some way to see that. Then you just need to make sure the address parameters are getting passed correctly in DoExpressCheckoutPayment.
If you like, you might want to take a look at my PHP class library for PayPal. Might kinda suck to start over with another library, but it makes it very quick and easy. It has files prepared with all the parameters and everything ready to go so all you need to do is fill in the values and it'll work every time. :)
After some furious research, I was able to figure out the problem using Paypal's API explorer. As it turns out, setting ->Address on the SetExpressCheckoutRequestType() object is deprecated. The correct method is to set ->ShipToAddress for your PaymentDetailsType() object.
In my case, however, the reason that nothing was working was because I had my address wrong [slaps palm into forehead]. My zip, while in the region of Columbus, OH is technically in Dublin, OH. So, Paypal was generating an error.
Paypal wasn't showing me error information, however, so I had no way to know what in particular was causing the error. This is where the API explorer came in handy; I filled in the API explorer and tried my request--and it gave me detailed error information.
Since then, I've also found out that I can see detailed error information simply by using:
var_dump($setECResponse);

Getting currency conversion data from Yahooapis now that iGoogle is gone

Up until yesterday I had a perfectly working budget organizer site/app working with iGoogle.
Through PHP, using the following little line
file_get_contents('http://www.google.com/ig/calculator?hl=en&q=1usd=?eur');
and similar I was able to get all I needed.
As of today, this is no longer working. When I looked into the issue, what has happened is that Google has retired iGoogle. Bummer!
Anyway, I was looking around elsewhere but I can't find anything that fits my needs. I would REALLY love to just fix it and get it running again by just switching this one line of code (i.e. changing the Google address with the address of some other currency API available) but it seems like none does.
The API from rate-exchange.appspot.com seems like it could be a iGoogle analog but, alas, it never works. I keep getting an "Over Quota" message.
(Here comes an initial question: anybody out there know of a simple, reliable, iGoogle-sort API?)
So I guess the natural thing would be to the Yahoo YQL feature (at least I suppose it is as reliable).
Yahoo's queries look like this:
http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "USDJPY", "USDBGN")&env=store://datatables.org/alltableswithkeys
What I really can't figure out is how to parse this data. It outputs an XML.
What I used to have is this:
function exchange($inputAmount,$inputCurrency,$outputCurrency) {
$exchange = file_get_contents('http://www.google.com/ig/calculator?hl=en&q='.$inputAmount.$inputCurrency.'=?'.$outputCurrency);
$exchange = explode('"', $exchange);
$exchange = explode('.', $exchange['3']);
$exchange[0] = str_replace(" ", "",preg_replace('/\D/', '', $exchange[0]));
if(isset($exchange[1])){
$exchange[1] = str_replace(" ", "",preg_replace('/\D/', '', $exchange[1]));
$exchange = $exchange[0].".".$exchange[1];
} else{
$exchange = $exchange[0];
}
return $exchange;
}
So the user was able to get the exchange rate from an input currency such as "USD" and an output currency such as "EUR" on a specific amount of money. As I said, this was working swimmingly up until yesterday night.
Any ideas?
Never mind! Solved it!
For anyone interested, here's what I did to get my code to work (with the least chnges possible) with the Yahoo YQL:
// ** GET EXCHANGE INFO FROM YAHOO YQL ** //
$url = 'http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "EURUSD")&env=store://datatables.org/alltableswithkeys'; //<-- Get the YQL info from Yahoo (here I'm only interested in converting from USD to EUR and vice-versa; you should add all conversion pairs you need).
$xml = simplexml_load_file($url) or die("Exchange feed not loading!"); //<-- Load the XML file into PHP variable.
$exchange = array(); //<-- Build an array to hold the data we need.
for($i=0; $i<2; $i++): //<-- For loop to get data specific to each exchange pair (you should change 2 to the actual amount of pairs you're querying for).
$name = (string)$xml->results->rate[$i]->Name; //<-- Get the name of the pair and turn it into a string (this looks like this: "USD to EUR").
$rate = (string)$xml->results->rate[$i]->Rate; //<-- Do the same for the actual rate resulting from the conversion.
$exchange[$name] = $rate; //<-- Put the data pairs into the array.
endfor; //<-- End for loop. :)
// ** WORK WITH EXCHANGE INFO ** //
$toeur = array( //<-- Create new array specific for conversion to one of the units needed.
'usd' => $exchange['USD to EUR'], //<-- Create an array key for each unit used. In this case, in order to get the conversion of USD to EUR I ask for it from my $exchange array with the pair Name.
'eur' => 1); //<-- The way I coded the app, I found it more practical to also create a conversion for the unit into itself and simply use a 1, which translates into "do not convert"
$tousd = array(
'eur' => $exchange['EUR to USD'],
'usd' => 1);
This is basically all you need to get all the exchange info you want. After that, you use it all something like this:
amount*$toxxx['coin'];
So, say I wanted to know how many Euro is 100 USD right now:
100*$toeur['usd'];
Piece of cake!
Still a very useful solution by QuestionerNo27. Since early 2015, however, Yahoo YQL apparently slightly changed the XML output of their api. 'Name' now no longer translates into a string like 'USD to EUR', but to 'USD/EUR' and should in the code above be referenced this way:
$toeur = array(
'usd' => $exchange['USD/EUR']
instead of
$toeur = array(
'usd' => $exchange['USD to EUR']
and in a similar fashion for other currency conversions.
I created a routine to convert the currency based on #QuestionerNo27 http://jamhubsoftware.com/geoip/currencyconvertor.php?fromcur=USD&tocur=EUR&amount=1 you can consume this
<?php
$fromcur = $_GET['fromcur'];
$tocur = $_GET['tocur'];
$amt = $_GET['amount'];
// ** GET EXCHANGE INFO FROM YAHOO YQL ** //
$url = 'http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("'.$fromcur.$tocur.'")&env=store://datatables.org/alltableswithkeys'; //<-- Get the YQL info from Yahoo (here I'm only interested in converting from USD to EUR and vice-versa; you should add all conversion pairs you need).
$xml = simplexml_load_file($url) or die("Exchange feed not loading!"); //<-- Load the XML file into PHP variable.
$exchange = array(); //<-- Build an array to hold the data we need.
for($i=0; $i<2; $i++): //<-- For loop to get data specific to each exchange pair (you should change 2 to the actual amount of pairs you're querying for).
$name = (string)$xml->results->rate[$i]->Name; //<-- Get the name of the pair and turn it into a string (this looks like this: "USD to EUR").
$rate = (string)$xml->results->rate[$i]->Rate; //<-- Do the same for the actual rate resulting from the conversion.
$exchange[$name] = $rate; //<-- Put the data pairs into the array.
endfor; //<-- End for loop. :)
// ** WORK WITH EXCHANGE INFO ** //
$conv = $fromcur . '/' . $tocur;
$toeur = array( //<-- Create new array specific for conversion to one of the units needed.
$tocur => $amt*$exchange[$conv], //<-- Create an array key for each unit used. In this case, in order to get the conversion of USD to EUR I ask for it from my $exchange array with the pair Name.
$fromcur => $amt,
"ex_amt" =>$amt*$exchange[$conv]); //<-- The way I coded the app, I found it more practical to also create a conversion for the unit into itself and simply use a 1, which translates into "do not convert"
echo json_encode($toeur);
?>

Categories