I'm sending a string of data via CURL using data from post, and receiving a response in a string as well which is in the form on an array. I'm trying to convert such response into an actual Array. Heres the code I have so far:
the response string im getting is this:
Test transaction_id="2401_02-29-12_22:28:34_0" action="payment"
result="success" to_from="to" amount="205.00" gross="205.00"
net="-0.85" custom="" business="XXXX#XXXX.com" item_name="XXXXX.XXX"
item_code="Product Name 3," quantity="1" transaction_type="authorized
payment" transaction_status="pending" transaction_date="2012-02-29
22:28:34" processing_rate="0.85" discount_fee="0.00"
first_name="TESTNAME" last_name="TESTLNAME" address="TESTADDRESS"
city="TESTCITY" state_or_province="AL" country="US"
zip_or_postal_code="12345" phone="1234562002" email="email#wemail.es"
shipment="yes" shipping_address="TESTADDRESS" shipping_city="TESTCITY"
shipping_state_or_province="AL" shipping_country="US"
shipping_zip_or_postal_code="12345" processing_time="0.2187"
And the code im using to get such response is
<?php
// Get variables from POST array into a string
$post_str = "action=payment&business=" .urlencode($this->input->post('business'))
."&vericode=" .urlencode($this->input->post('vericode'))
."&item_name=" .urlencode($this->input->post('item_name'))
."&item_code=" .urlencode($this->input->post('item_code'))
."&quantity=" .urlencode($this->input->post('quantity'))
."&amount=" .urlencode($this->input->post('amount'))
."&cc_type=" .urlencode($this->input->post('cc_type'))
."&cc_number=" .urlencode($this->input->post('cc_number'))
."&cc_expdate=" .urlencode($this->input->post('cc_expdate_year')).urlencode($this->input->post('cc_expdate_month'))
."&cc_security_code=" .urlencode($this->input->post('cc_security_code'))
."&shipment=" .urlencode($this->input->post('shipment'))
."&first_name=" .urlencode($this->input->post('first_name'))
."&last_name=" .urlencode($this->input->post('last_name'))
."&address=" .urlencode($this->input->post('address'))
."&city=" .urlencode($this->input->post('city'))
."&state_or_province=" .urlencode($this->input->post('state_or_province'))
."&zip_or_postal_code=" .urlencode($this->input->post('zip_or_postal_code'))
."&country=" .urlencode($this->input->post('country'))
."&shipping_address=" .urlencode($this->input->post('shipping_address'))
."&shipping_city=" .urlencode($this->input->post('shipping_city'))
."&shipping_state_or_province=" .urlencode($this->input->post('shipping_state_or_province'))
."&shipping_zip_or_postal_code=".urlencode($this->input->post('shipping_zip_or_postal_code'))
."&shipping_country=" .urlencode($this->input->post('shipping_country'))
."&phone=" .urlencode($this->input->post('phone'))
."&email=" .urlencode($this->input->post('email'))
."&ip_address=" .urlencode($this->input->post('ip_address'))
."&website_unique_id=" .urlencode($this->input->post('website_unique_id'));
// Send URL string via CURL
$backendUrl = "https://www.veripayment.com/integration/index.php";
$this->curl->create($backendUrl);
$this->curl->post($post_str);
// get response from API
$return_str = $this->curl->execute();
?>
If the response you're receiving has elements separated by a space you might use
function parse($response)
{
$result = array();
$resparray = explode(' ', $response);
if ($resparray)
{
foreach ($resparray as $resp) {
$keyvalue = explode('=', $resp);
$result[$keyvalue[0]] = str_replace('"', '', $keyvalue[1]);
}
}
return $result;
}
Edited and corrected, Here's the output
Array ( [transaction_id] => 2401_02-29-12_22:28:34_0 [action] => payment [result] => success [to_from] => to [amount] => 205.00 [gross] => 205.00 [net] => -0.85 [custom] => [business] => XXXX#XXXX.com [item_name] => XXXXX.XXX [item_code] => Product [Name] => [3,"] => [quantity] => 1 [transaction_type] => authorized [payment"] => [transaction_status] => pending [transaction_date] => 2012-02-29 [22:28:34"] => [processing_rate] => 0.85 [discount_fee] => 0.00 [first_name] => TESTNAME [last_name] => TESTLNAME [address] => TESTADDRESS [city] => TESTCITY [state_or_province] => AL [country] => US [zip_or_postal_code] => 12345 [phone] => 1234562002 [email] => email#wemail.es [shipment] => yes [shipping_address] => TESTADDRESS [shipping_city] => TESTCITY [shipping_state_or_province] => AL [shipping_country] => US [shipping_zip_or_postal_code] => 12345 [processing_time] => 0.2187
Related
I have a Json Script with an Array inside and Array which looks like this shortened:
Array
(
[assets] => Array
(
[CGGD.AS] => Array
(
[shortName] => iShares Global Govt Bond Climat
[sector] =>
[industry] =>
[country] =>
[longBusinessSummary] =>
[currency] => USD
[marketCap] =>
[logo_url] =>
[Anlageklasse] => Anleihen
[Anmerkungen] => Staatsanleihen Welt
[Nachhaltigkeit] => 1
[Ist_Alternative] => 1
[weights] => 0.86563025602977
)
[SUOE.MI] => Array
(
[shortName] => ISHARES EUR CORP BOND SRI UCITS
[sector] =>
[industry] =>
[country] =>
[longBusinessSummary] =>
[currency] => EUR
[marketCap] =>
[logo_url] =>
[Anlageklasse] => Anleihen
[Anmerkungen] => Unternehmensnaleihen EUR
[Nachhaltigkeit] => 1
[Ist_Alternative] => 1
[weights] => -0.47997445382071
)
)
[risk] => 0.05323390949106
[return] => 1.1125842376311
)
Now I want to work with the single variables shortName, industry, etc.
When I tried to call the function with
print_r($json_data['assets']['CGGD.AS']['shortName']);
it worked perfectly fine. When I use
print_r($_POST['assets'][0][0]);
it is not working at all and gives me the following warning:
Warning: Undefined array key "assets" in
C:\xampp\htdocs\test\ergebnisdarstellung.php on line 52
Warning: Trying to access array offset on value of type null in
C:\xampp\htdocs\test\ergebnisdarstellung.php on line 52
The problem I have is that I will not know what name will be in the second brackets like CGGD.AS and because of this I can not use the working function. I will not now how long the array is either and numbers are not working. Because of this I do not know how to call the single variabless without using the name.
How can I call the function?
To get all shortName you can loop your array:
foreach ($json_data['assets'] as $key => $data) {
print_r($data['shortName']);
}
If you want just shortName of first element, then use current:
$item = current($json_data['assets']);
print_r($item['shortName']);
$arr = [
'assets' => [
'CGGD.AS' => [
'shortName' => 'iShares Global Govt Bond Climat',
// other fields omitted
],
'SUOE.MI' => [
'shortName' => 'ISHARES EUR CORP BOND SRI UCITS',
// other fields omitted
]
],
'risk' => 0.05323390949106,
'return' => 1.1125842376311
];
$assetsKeys = array_keys($arr['assets']);
$shortNames = array_column($arr['assets'], 'shortName');
$result = array_combine($assetsKeys, $shortNames);
print_r($result);
// This will print:
// Array
// (
// [CGGD.AS] => iShares Global Govt Bond Climat
// [SUOE.MI] => ISHARES EUR CORP BOND SRI UCITS
// )
I'm pulling results from an XML SOAP service which returns results in structure that doesn't work too well with encoding the result to json then decoding into an array.
Here's an example of the output I've rendered by running the following function on my results:
$result[implode('/',$keys)] = $val;
Array
(
[accountList/accountNo] => 0610010000048744
[accountList/accountOpeningDate] => 2014-09-01T00:00:00+03:00
[accountList/accountStatus] => DORMANT
[accountList/arrearAmount] => 80000.0
[accountList/arrearDays] => 30
[accountList/balanceAmount] => 120000.0
[accountList/disputed] => false
[accountList/isMyAccount] => false
[accountList/lastPaymentDate] => 2015-01-23T00:00:00+03:00
[accountList/listingDate] => 2014-09-30T00:00:00+03:00
[accountList/pastDueDate] => 1900-01-01T00:00:00+03:00
[accountList/principalAmount] => 300000.0
[accountList/scheduledPaymentAmount] => 0.0
[accountList/tradeSector] => Bank Sector Bureau
[accountList/worstArrear] => 30
[accountList/currency] => KES
[personalProfile/crn] => 79908
[personalProfile/dateOfBirth] => 1959-01-01T00:00:00+02:45
[personalProfile/fullName] => Surname 79908 OtherNames 79908
[personalProfile/gender] => F
[personalProfile/nationalID] => ID79908
[summary/npaAccounts/mySector] => 2
[summary/npaAccounts/otherSectors] => 0
[summary/npaTotalValueList/currency] => KES
[summary/npaTotalValueList/mySector] => 120000.0
[summary/npaTotalValueList/otherSectors] => 0.0
[summary/openAccounts/mySector] => 2
[summary/openAccounts/otherSectors] => 0
)
Because the results and keys always vary depending on request I make to the server, I'd like to build a multidimensional array through a recursive function, in some instances the keys eg. accountList may have multiple values
An expected result would look something like this:
Array
(
[accountList] => Array
(
[accountNo] => 0610010000048744
[accountOpeningDate] => 2014-09-01T00:00:00+03:00
[accountStatus] => DORMANT
[arrearAmount] => 80000.0
[arrearDays] => 30
[balanceAmount] => 120000.0
[disputed] => false
[isMyAccount] => false
[lastPaymentDate] => 2015-01-23T00:00:00+03:00
[listingDate] => 2014-09-30T00:00:00+03:00
[pastDueDate] => 1900-01-01T00:00:00+03:00
[principalAmount] => 300000.0
[scheduledPaymentAmount] => 0.0
[tradeSector] => Bank, Sector Bureau
[worstArrear] => 30
[currency] => KES
)
Array
(
[accountNo] => 0610010000048788
[accountOpeningDate] => 2014-09-01T00:00:00+03:00
[accountStatus] => ACTIVE
[arrearAmount] => 10000.0
[arrearDays] => 90
[balanceAmount] => 10000.0
[disputed] => TRUE
[isMyAccount] => false
[lastPaymentDate] => 2015-01-23T00:00:00+03:00
[listingDate] => 2014-09-30T00:00:00+03:00
[pastDueDate] => 1900-01-01T00:00:00+03:00
[principalAmount] => 300000.0
[scheduledPaymentAmount] => 0.0
[tradeSector] => Bank, Sector Bureau
[worstArrear] => 30
[currency] => KES
)
[personalProfile] => Array
(
[crn] => 79908
[dateOfBirth] => 1959-01-01T00:00:00+02:45
[fullName] => Surname, 79908 OtherNames 79908
[gender] => F
[nationalID] => ID79908
)
)
I think you are trying to achieve this thing.
Try this code snippet here
explode("/", $key) this will return array which will contain two values.
list($first,$second)=explode("/", $key); and through this i am putting those values, one in $first and other in $second.
<?php
ini_set('display_errors', 1);
$data=Array
(
"accountList/accountNo"=>"0610010000048744",
"accountList/accountOpeningDate"=>"2014-09-01T00:00:00+03:00",
"accountList/accountStatus"=>"DORMANT",
"accountList/arrearAmount"=>"80000.0",
"accountList/arrearDays"=>"30",
"accountList/balanceAmount"=>"120000.0",
"accountList/disputed"=>"false",
"accountList/isMyAccount"=>"false",
"accountList/lastPaymentDate"=>"2015-01-23T00:00:00+03:00",
"accountList/listingDate"=>"2014-09-30T00:00:00+03:00",
"accountList/pastDueDate"=>"1900-01-01T00:00:00+03:00",
"accountList/principalAmount"=>"300000.0",
"accountList/scheduledPaymentAmount"=>"0.0",
"accountList/tradeSector"=>"Bank, Sector Bureau",
"accountList/worstArrear"=>"30",
"accountList/currency"=>"KES",
"personalProfile/crn"=>"79908",
"personalProfile/dateOfBirth"=>"1959-01-01T00:00:00+02:45",
"personalProfile/fullName"=>"Surname, 79908 OtherNames 79908",
"personalProfile/gender"=>"F",
"personalProfile/nationalID"=>"ID79908",
"sample/data/data1"=>"ID79908",//added a sample data
);
$result=array();
foreach($data as $key => $value)
{
$string="";
$numberOfWords=explode("/", $key);
foreach($numberOfWords as $newValue)
{
$string.="['$newValue']";
}
eval('$result'.$string."= \"$value\";");
}
print_r($result);
The way you want to build your array is as follows. The reason is that you want things like "accountList" and "personalProfile" to be unique keys within the array, much like they would be in a relational database.
$array = $array('accountList'=>array("accountNo"=>"0610010000048744",
"accountOpenDate"=>"2014-09-
01T00:00:00+03:00"),array("personalProfile"=>array("...and so on."));
I need to add order data in OpenCart 2.1.0.1 template on checkout/success page. I added the below code in view/theme/name/template/common/success.tpl but it is not showing order data, (values are empty because there is no order id in $this->session->data).
<?php if(!empty($orderid)) echo $orderid; ?>
<?php if(!empty($email)) echo $email; ?>
<?php if(!empty($fname)) echo $fname; ?>
<?php if(!empty($lname)) echo $lname; ?>
In /catalog/controller/checkout/success.php I have defined these PHP variables:
$this->data['orderid'] = $$this->session->data['order_id'];
$this->data['fname'] = $this->session->data['guest']['firstname'];
$this->data['lname'] = $this->session->data['guest']['lastname'];
$this->load->model('account/order');
$order = $this->model_account_order->getOrder($this->session->data['order_id']);
if($order) {
$this->data['email'] = $order['email'];
}
Can anyone guide what am I missing and why these values are not loading in.tpl file, and what is the solution. Even hard coded values are also not retrieved in .tpl.
Values of $this->session->data:
(
[language] => en
[currency] => USD
[user_id] => 9
[token] => 5ZiNOGeVjCdg4gefNkDLcHzF1zMUVKgA
[account] => guest
[payment_address] => Array
(
[firstname] => sdfsdf
[lastname] => adfafa
[company] =>
[address_1] => test test test
[address_2] =>
[postcode] => 34324
[city] => sdfsdfd
[country_id] => 216
[zone_id] => 3396
[country] => Turkmenistan
[iso_code_2] => TM
[iso_code_3] => TKM
[address_format] =>
[custom_field] => Array
(
)
[zone] => Ahal Welayaty
[zone_code] => A
)
[shipping_address] => Array
(
[firstname] => sdfsdf
[lastname] => adfafa
[company] =>
[address_1] => test test test
[address_2] =>
[postcode] => 34324
[city] => sdfsdfd
[country_id] => 216
[zone_id] => 3396
[country] => Turkmenistan
[iso_code_2] => TM
[iso_code_3] => TKM
[address_format] =>
[zone] => Ahal Welayaty
[zone_code] => A
[custom_field] => Array
(
)
)
)
Correct variable name
Opencart 2.0 and up doesn't use $this->data for templates. Instead simply use $data. SO instead of:
$this->data['hardcoded'] = "HARD CODED";
You can write:
$data['hardcoded'] = "HARD CODED";
Position of code
All order data is cleared at the top of the controller so if you need to access it make sure you define those variables before:
if (isset($this->session->data['order_id'])) {
Efficiency & Accuracy of data
Normally, $this->session->data['guest'] is only defined if customer is not logged in. The best way to use order data would be to get data from the order itself and assign it to a single array since all the conditionals have already been dealt with when it was created. This saves you the trouble of re-defining each variable and checking logged in status, etc:
$this->load->model('checkout/order');
$data['order'] = $this->model_checkout_order->getOrder($this->session->data['order_id']);
Then in your tpl you can access anything about the order in the $order array:
$order['order_id']
$order['firstname']
is the $data['order'] bit right in
$this->load->model('checkout/order');
$data['order'] = $this->model_checkout_order->getOrder($this->session->data['order_id']);
should it not be?
$this->load->model('checkout/order');
$order = $this->model_checkout_order->getOrder($this->session->data['order_id']);
I am using third party api to get city lists into my dropdown. I am getting response from third party api in this form
"TopDestination":"14621
</cityId>Amsterdam
</cityName>NL
</countryCode>Netherlands
</countryName>AMS
</cityCode>
My response is in a variable called $res and when i am trying to print like this
$res->TopDestination->cityId;
But it is not printing anything. If i am trying to print
$res->TopDestination;
It is printing results like this
14621AmsterdamNLNetherlandsAMS
What should i use to print city id ?
My response from api is like this
{"Error":{"ErrorCode":0,"ErrorMessage":""},"Status":1,"TokenId":"59831ca1-37e8-42fd-8350-0b3699b86505","TopDestination":"14621<\/cityId>Amsterdam<\/cityName>NL<\/countryCode>Netherlands<\/countryName>AMS<\/cityCode><\/City>17249<\/cityId>Antalya<\/cityName>TR<\/countryCode>Turkey<\/countryName>ANTA<\/cityCode><\/City>9434<\/cityId>Athens<\/cityName>GR<\/countryCode>Greece<\/countryName>ATH<\/cityCode><\/City>10142<\/cityId>Bali<\/cityName>ID<\/countryCode>Indonesia<\/countryName>ABAL<\/cityCode><\/City>16974<\/cityId>Bangkok<\/cityName>TH<\/countryCode>Thailand<\/countryName>BKK<\/cityCode><\/City>3518<\/cityId>Barcelona<\/cityName>ES<\/countryCode>Spain<\/countryName>BCN<\/cityCode><\/City>23131<\/cityId>Basel<\/cityName>CH<\/countryCode>Switzerland<\/countryName>BSL<\/cityCode><\/City>23884<\/cityId>Beijing<\/cityName>CN<\/countryCode>China<\/countryName>PEK<\/cityCode><\/City>13551<\/cityId>Beirut<\/cityName>LB<\/countryCode>Lebanon<\/countryName>BEY<\/cityCode><\/City>1996<\/cityId>Berlin<\/cityName>DE<\/countryCode>Germany<\/countryName>BER<\/cityCode><\/City>24602<\/cityId>Brussels<\/cityName>BE<\/countryCode>Belgium<\/countryName>BRU<\/cityCode><\/City>10085<\/cityId>Budapest<\/cityName>HU<\/countryCode>Hungary<\/countryName>BUD<\/cityCode><\/City>2418<\/cityId>Cairo<\/cityName>EG<\/countryCode>Egypt<\/countryName>CAI<\/cityCode><\/City>32443<\/cityId>Cape Town<\/cityName>ZA<\/countryCode>South Africa<\/countryName>CPT<\/cityCode><\/City>20491<\/cityId>Chicago<\/cityName>US<\/countryCode>United States<\/countryName>CHI<\/cityCode><\/City>125<\/cityId>Cologne<\/cityName>DE<\/countryCode>Germany<\/countryName>CGN<\/cityCode><\/City>13616<\/cityId>Colombo<\/cityName>LK<\/countryCode>Sri Lanka<\/countryName>CMB<\/cityCode><\/City>2142<\/cityId>Copenhagen<\/cityName>DK<\/countryCode>Denmark<\/countryName>CPH<\/cityCode><\/City>25921<\/cityId>Dubai<\/cityName>AE<\/countryCode>United Arab Emirates<\/countryName>DXB<\/cityCode><\/City>32515<\/cityId>Durban<\/cityName>ZA<\/countryCode>South Africa<\/countryName>DUR<\/cityCode><\/City>27352<\/cityId>Dusseldorf<\/cityName>DE<\/countryCode>Germany<\/countryName>DUS<\/cityCode><\/City>8030<\/cityId>Edinburgh<\/cityName>GB<\/countryCode>United Kingdom<\/countryName>EDI<\/cityCode><\/City>11213<\/cityId>Florence<\/cityName>IT<\/countryCode>Italy<\/countryName>FLR<\/cityCode><\/City>22753<\/cityId>Frankfurt<\/cityName>DE<\/countryCode>Germany<\/countryName>FRA<\/cityCode><\/City>23435<\/cityId>Geneva<\/cityName>CH<\/countryCode>Switzerland<\/countryName>GVA<\/cityCode><\/City>26698<\/cityId>Gold Coast<\/cityName>AU<\/countryCode>Australia<\/countryName>OOL<\/cityCode><\/City>23960<\/cityId>Guangzhou<\/cityName>CN<\/countryCode>China<\/countryName>CAN<\/cityCode><\/City>379<\/cityId>Hamburg<\/cityName>DE<\/countryCode>Germany<\/countryName>HAM<\/cityCode><\/City>9926<\/cityId>Hong Kong<\/cityName>HK<\/countryCode>Hong Kong<\/countryName>HKG<\/cityCode><\/City>26996<\/cityId>Innsbruck<\/cityName>AT<\/countryCode>Austria<\/countryName>INN<\/cityCode><\/City>23037<\/cityId>Interlaken<\/cityName>CH<\/countryCode>Switzerland<\/countryName>INTE<\/cityCode><\/City>17306<\/cityId>Istanbul<\/cityName>TR<\/countryCode>Turkey<\/countryName>IST<\/cityCode><\/City>32569<\/cityId>Johannesburg<\/cityName>ZA<\/countryCode>South Africa<\/countryName>JNB<\/cityCode><\/City>15054<\/cityId>Kathmandu<\/cityName>NP<\/countryCode>Nepal<\/countryName>KTM<\/cityCode><\/City>14386<\/cityId>Kuala Lumpur<\/cityName>MY<\/countryCode>Malaysia<\/countryName>KUL<\/cityCode><\/City>35827<\/cityId>Kuwait<\/cityName>KW<\/countryCode>Kuwait<\/countryName>KWI<\/cityCode><\/City>14285<\/cityId>Langkawi<\/cityName>MY<\/countryCode>Malaysia<\/countryName>LANK<\/cityCode><\/City>32827<\/cityId>Las Vegas<\/cityName>US<\/countryCode>United States<\/countryName>LAS<\/cityCode><\/City>9245<\/cityId>London<\/cityName>GB<\/countryCode>United Kingdom<\/countryName>LON<\/cityCode><\/City>34549<\/cityId>London<\/cityName>CA<\/countryCode>Canada<\/countryName>YXU<\/cityCode><\/City>18631<\/cityId>Los Angeles<\/cityName>US<\/countryCode>United States<\/countryName>LAX<\/cityCode><\/City>23273<\/cityId>Lucerne<\/cityName>CH<\/countryCode>Switzerland<\/countryName>LUCE<\/cityCode><\/City>13674<\/cityId>Macau<\/cityName>MO<\/countryCode>Macau<\/countryName>MFM<\/cityCode><\/City>3000<\/cityId>Madrid<\/cityName>ES<\/countryCode>Spain<\/countryName>MAD<\/cityCode><\/City>14254<\/cityId>Mauritius<\/cityName>MU<\/countryCode>Mauritius<\/countryName>MRUW<\/cityCode><\/City>26916<\/cityId>Melbourne<\/cityName>AU<\/countryCode>Australia<\/countryName>MEL<\/cityCode><\/City>11297<\/cityId>Milan<\/cityName>IT<\/countryCode>Italy<\/countryName>MIL<\/cityCode><\/City>266<\/cityId>Munich<\/cityName>DE<\/countryCode>Germany<\/countryName>MUC<\/cityCode><\/City>13443<\/cityId>Nairobi<\/cityName>KE<\/countryCode>Kenya<\/countryName>NBO<\/cityCode><\/City>28985<\/cityId>New York<\/cityName>US<\/countryCode>United States<\/countryName>NYC<\/cityCode><\/City>4419<\/cityId>Nice<\/cityName>FR<\/countryCode>France<\/countryName>NCE<\/cityCode><\/City>19533<\/cityId>Orlando<\/cityName>US<\/countryCode>United States<\/countryName>ORL<\/cityCode><\/City>4775<\/cityId>Paris<\/cityName>FR<\/countryCode>France<\/countryName>PAR<\/cityCode><\/City>36773<\/cityId>Pattaya Beach<\/cityName>TH<\/countryCode>Thailand<\/countryName>PATT<\/cityCode><\/City>14321<\/cityId>Penang<\/cityName>MY<\/countryCode>Malaysia<\/countryName>PEN<\/cityCode><\/City>17093<\/cityId>Phuket<\/cityName>TH<\/countryCode>Thailand<\/countryName>PHUW<\/cityCode><\/City>24332<\/cityId>Prague<\/cityName>CZ<\/countryCode>Czech Republic<\/countryName>PRG<\/cityCode><\/City>12771<\/cityId>Rome<\/cityName>IT<\/countryCode>Italy<\/countryName>ROM<\/cityCode><\/City>27022<\/cityId>Salzburg<\/cityName>AT<\/countryCode>Austria<\/countryName>SZG<\/cityCode><\/City>18857<\/cityId>San Diego<\/cityName>US<\/countryCode>United States<\/countryName>SAN<\/cityCode><\/City>18861<\/cityId>San Francisco<\/cityName>US<\/countryCode>United States<\/countryName>SFO<\/cityCode><\/City>23909<\/cityId>Shanghai<\/cityName>CN<\/countryCode>China<\/countryName>SHA<\/cityCode><\/City>23976<\/cityId>Shenzhen<\/cityName>CN<\/countryCode>China<\/countryName>SHEN<\/cityCode><\/City>16532<\/cityId>Singapore<\/cityName>SG<\/countryCode>Singapore<\/countryName>SIN<\/cityCode><\/City>34326<\/cityId>Sydney<\/cityName>AU<\/countryCode>Australia<\/countryName>SYD<\/cityCode><\/City>13420<\/cityId>Tokyo<\/cityName>JP<\/countryCode>Japan<\/countryName>TYO<\/cityCode><\/City>34661<\/cityId>Toronto<\/cityName>CA<\/countryCode>Canada<\/countryName>YTO<\/cityCode><\/City>25561<\/cityId>Vancouver<\/cityName>CA<\/countryCode>Canada<\/countryName>YVR<\/cityCode><\/City>11501<\/cityId>Venice<\/cityName>IT<\/countryCode>Italy<\/countryName>VCE<\/cityCode><\/City>27059<\/cityId>Vienna<\/cityName>AT<\/countryCode>Austria<\/countryName>VIE<\/cityCode><\/City>23418<\/cityId>Zermatt<\/cityName>CH<\/countryCode>Switzerland<\/countryName>ZERM<\/cityCode><\/City>23424<\/cityId>Zurich<\/cityName>CH<\/countryCode>Switzerland<\/countryName>ZRH<\/cityCode><\/City><\/Cities>"}
The problem is with the JSON response from the API. Your array $res['TopDestination'] contains just a string, thus you cannnot access "cityId". You have to PROCESS the $res['TopDestination'].
Based on your JSON this should work (it's tested!):
<?php
// $json = result from API (a valid JSON string!)
$res=json_decode($json, true);
// get TopDestination string into an array
$data=explode("</City>", $res["TopDestination"]);
array_pop($data);
// create a new Database of cities
$cities=array();
foreach ($data as $d) {
$tmp=explode("</cityId>",$d);
$city_id=$tmp[0];
$tmp=explode("</cityName>", $tmp[1]);
$city_name=$tmp[0];
$tmp=explode("</countryCode>", $tmp[1]);
$country_code=$tmp[0];
$tmp=explode("</countryName>", $tmp[1]);
$country_name=$tmp[0];
$city_code=$tmp[1];
// add the city info in the database
$cities[]=array(
"cityId" => $city_id,
"cityName" => $city_name,
"cityCode" => $city_code,
"countryCode" => $country_code,
"countryName" => $country_name,
);
}
// print the database array to check it
echo "<pre>";
print_r($cities);
echo "</pre>";
?>
The result is... :)
Array
(
[0] => Array
(
[cityId] => 14621
[cityName] => Amsterdam
[cityCode] => AMS
[countryCode] => NL
[countryName] => Netherlands
)
[1] => Array
(
[cityId] => 17249
[cityName] => Antalya
[cityCode] => ANTA
[countryCode] => TR
[countryName] => Turkey
)
[2] => Array
(
[cityId] => 9434
[cityName] => Athens
[cityCode] => ATH
[countryCode] => GR
[countryName] => Greece
)
[3] => Array
(
...
I am using curl to get an external XML document and convert it to an array.
The code works almost perfect, apart from one node in the XML isn't being processed and put in my array.
Under <drivers> there is a code for each driver: <driver code="TM1"> but this doesn't get picked up by my array as an #attribute array like the others such as <collection date="20160324">
Does anybody know why this is happening?
XML:
<findit xmlns="http://www.URL.COM" version="8" type="TIX" date="20160323">
<account code="XXXXXX">
<customers>
<customer code="12345">
<status code="0">Success</status>
<logistic-jobs>
<logistic-job id="12345" date="20160324" status="PLA" modified="201603231420">
<number>
<number1>479599</number1>
<number3>11221</number3>
</number>
<collection date="20160324" time="0500">
<name>JOHN SMITH</name>
<address1>UNIT 3 DAVEY ROAD</address1>
<address2>FIELDS END BUSINESS PARK</address2>
<address3>GOLDTHORPE</address3>
<address4>ROTHERHAM</address4>
<address5>S63 0JF</address5>
</collection>
<delivery date="20160324" time="1200">
<address1>EXAMPLE</address1>
<address2>GLENEAFLES FARM</address2>
<address3>GLENEAGLES CLOSE</address3>
<address4>STANWELL, MIDDLESEX</address4>
<address5>TW19 7PD</address5>
</delivery>
<extra>
<address1>45FT C/SIDER</address1>
<address2>No</address2>
<address4>CEMENT</address4>
</extra>
<drivers>
<driver code="TM1">DAVE SMITH (DAYS)</driver>
</drivers>
<load weight="27600.00" volume="0.00">
<pallets full="23" half="0" quarter="0" blue="0" oversize="0"/>
</load>
</logistic-job>
</logistic-jobs>
</customer>
</customers>
</account>
</findit>
PHP:
$job_array = json_decode(json_encode(simplexml_load_string($xml)), true);
if(is_array($job_array['account']['customers']['customer'])) {
// Foreach customer in array
foreach($job_array['account']['customers']['customer'] as $i => $customer) {
// If status is set to success
if($customer['status'] == "Success") {
// For each job
foreach($customer['logistic-jobs']['logistic-job'] as $i => $job) {
echo '<pre>'; print_r($job); echo '</pre>';
}
}
}
}
OUTPUT:
Array
(
[#attributes] => Array
(
[id] => 12345
[date] => 20160324
[status] => PLA
[modified] => 201603231420
)
[number] => Array
(
[number1] => 479599
[number3] => 11221
)
[collection] => Array
(
[#attributes] => Array
(
[date] => 20160324
[time] => 0500
)
[name] => JOHN SMITH
[address1] => UNIT 3 DAVEY ROAD
[address2] => FIELDS END BUSINESS PARK
[address3] => GOLDTHORPE
[address4] => ROTHERHAM
[address5] => S63 0JF
)
[delivery] => Array
(
[#attributes] => Array
(
[date] => 20160324
[time] => 1200
)
[address1] => EXAMPLE
[address2] => GLENEAFLES FARM
[address3] => GLENEAGLES CLOSE
[address4] => STANWELL, MIDDLESEX
[address5] = TW19 7PD
)
[extra] => Array
(
[address1] => 45FT C/SIDER
[address2] => No
[address4] => CEMENT
)
[drivers] => Array
(
[driver] => DAVE SMITH (DAYS)
)
[load] => Array
(
[#attributes] => Array
(
[weight] => 21509.00
[volume] => 0.00
)
[pallets] => Array
(
[#attributes] => Array
(
[full] => 52
[half] => 0
[quarter] => 0
[blue] => 0
[oversize] => 0
)
)
)
)
I have a simple answer for you: don't convert XML to an array. SimpleXML has a really useful API for traversing through the XML document and finding the data you want; throw away the horrible json_decode(json_encode( hack and look at the examples in the PHP manual.
In this case, echo $driver would give you the contents (driver name) and echo $driver['code'] would give you the attribute value; clearly, a plain array can't have that convenient magic, which is why converting to one is giving you problems.
Just remember that print_r will also hide things from you, and you might want a dedicated debugging function.
Here's an example (with live demo) of getting the code and name of each driver:
$job_simple = simplexml_load_string($xml);
if(isset($job_simple->account->customers->customer)) {
// Foreach customer in array
foreach($job_simple->account->customers->customer as $i => $customer) {
// If status is set to success
if((string)$customer->status == "Success") {
// For each job
foreach($customer->{'logistic-jobs'}->{'logistic-job'} as $i => $job) {
echo "<ul>\n";
foreach ( $job->drivers->driver as $driver ) {
echo "<li> {$driver['code']}: $driver\n";
}
echo "</ul>\n";
}
}
}
}