I have an xml response for a DHL tracking and i want to echo specific elements on my php page.
I use the following code to print out the tracking results without formatting:
print_r($response);
The xml response looks like this:
Array
(
[TrackingResponse] => Array
(
[xmlns:req] => http://www.dhl.com
[xmlns:xsi] => http://www.w3.org/2001/XMLSchema-instance
[xsi:schemaLocation] => http://www.dhl.com TrackingResponse.xsd
[Response] => Array
(
[ServiceHeader] => Array
(
[MessageTime] => 2013-12-12T11:51:05+00:00
[MessageReference] => j2xfhcBpCE2yd9gbeC5tjqxIX8xjDpZ1
[SiteID] => iraqnova
)
)
[AWBInfo] => Array
(
[AWBNumber] => 8564385550
[Status] => Array
(
[ActionStatus] => success
)
[ShipmentInfo] => Array
(
[OriginServiceArea] => Array
(
[ServiceAreaCode] => FRA
[Description] => FRANKFURT - GERMANY
)
[DestinationServiceArea] => Array
(
[ServiceAreaCode] => MLA
[Description] => MALTA - MALTA
)
[ShipperName] => STANDARD CHARTERED BANK
[ShipperAccountNumber] => 144193851
[ConsigneeName] => BANK OF VALLETTA P.L.C
[ShipmentDate] => 2013-02-14T15:14:00
[Pieces] => 1
[Weight] => 0.08
[WeightUnit] => K
[GlobalProductCode] => U
[ShipmentDesc] => 1402130018
[DlvyNotificationFlag] => Y
[Shipper] => Array
(
[City] => Frankfurt/Main
[PostalCode] => 60486
[CountryCode] => DE
)
[Consignee] => Array
(
[City] => Santa Venera
[PostalCode] => 9030
[CountryCode] => MT
)
[ShipperReference] => Array
(
[ReferenceID] => Doc
)
)
)
)
)
I'm getting lost with so many foreach loops to get to the specific xml tags inside the [ShipmentInfo] tag:
foreach($response as $tag){
echo $tag['ShipmentInfo'];
}
The sample tracking number and info, from the DHL XML Service Validation website http://xmlpitest-ea.dhl.com/serviceval/jsps/main/Main_menu.jsp
Thank you,
$arr['TrackingResponse']['AWBInfo']['ShipmentInfo'] will lead to the shipment info and then iterate over this using foreach.
Like -
if(is_array($arr['TrackingResponse']['AWBInfo']['ShipmentInfo'])) {
foreach(is_array($arr['TrackingResponse']['AWBInfo']['ShipmentInfo']) as $shiptagkey=>$shiptagval)
{
echo $shiptagkey, " ", $shiptagval;
}
}
Although $shiptagval itself going to be an array so you need to care about this as well.
print_r($response ['TrackingResponse']['AWBInfo']['ShipmentInfo']);
or if you don't know the path: (pseudocode)
function findAndEcho($obj,$tag) {
for $obj as $key => $val {
if $key = $tag {
print_r($val)
}
else if is_array($val) {
findAndEcho($val,$tag)
}
}
}
Related
I have a response for ups address validation request as follows:
Array ( [meta] => Array ( [code] => 200 [error_message] => ) [data] => Array ( [city] => [errors] => Array ( [0] => Array ( [code] => [type] => [description] => The state is not supported in the Customer Integration Environment. ) ) [name] => [city_state_zip_match] => [residential] => [po_box] => [suggestions] => [zipcode] => [state] => [addr2] => [addr3] => [addr1] => [zipcode_addon] => [country] => [checks] => [match] => ) )
in PHP, how I do I get individual values like..
code and error_message name, residential, po_box, sate etc.
Thanks in advance
With an array like this
$arr = Array([meta] => Array ( [code] => 200 [error_message] => ));
This is equivalent to
$arr = ["meta" => ["code" => 200, "error_message" => ""]];
So to access the code we would do
$code = $arr["meta"]["code"];
Thank you.
It is working fine with the following code.
$json = <response from ups through rocketship.it>
print_r($json['meta']['code']);
print_r($json['meta']['error_message']);
print_r($json['data']['name']);
print_r($json['data']['po_box']);
print_r($json['data']['errors'][0]['description']);
if ($json['data']['po_box']){
echo "PO BOX: Yes";
}else{
echo "PO BOX: No";
}
I have two arrays
array_1 is multidimensional but the location of the value I need is
array_1['id']
array_2 is also multidimensional and the location is further down inside.
array_2['data']['id']
Now I am trying to execute my code only if (===) those 2 ID'S are identical.
Further Information is that this is a combination of 2 API'S but the code for the API'S is working fine because if I try to get information from both API'S it shows me.
Code:
$orders = $apiSeo->orders->get();
$parcels = $apiSend->parcels->get();
foreach($orders as $id => $order){
if(($orders[$id]['paymentStatus'] == 'paid') || ($orders[$id]['paymentIsPost'] == true)){
echo '<pre>';
var_export($orders[$id]['id']);
var_export($orders[$id]['lastname']);
var_export($orders[$id]['paymentStatus']);
var_export($orders[$id]['paymentIsPost']);
echo '</pre>';
}
}
what have I tried adding:
foreach($parcels as $id2 => $parcel){
if($orders[$id]['id'] === $parcels[$id2]['data']['order_id']){//}
}
and also no succes with array_key_exists or in_array.
My output with var_export or var_dump is nothing when adding these pieces of code. also no error while i have error reporting on. So I Am clueless where the mistake or miscode lies.
print_r request $parcels array
Array
(
[0] => Array
(
[id] => 1440143
[address] => xx
[address_divided] => Array
(
[street] => xx
[house_number] => 8
)
[city] => xx
[company_name] =>
[country] => Array
(
[iso_2] => NL
[iso_3] => NLD
[name] => Netherlands
)
[data] => Array
(
**[seoshop_order_id] => 15802836** HERE!
)
[date_created] => 03-03-2016 07:41:39
[email] => xx#live.nl
[name] => xx
[postal_code] => xx
[reference] => 0
[shipment] => Array
(
[id] => 10
[name] => DHL Complete with signature
)
[status] => Array
(
[id] => 1000
[message] => Ready to send
[history] =>
)
[telephone] => xx
[tracking_number] => JVGL0
[label] => Array
(
[normal_printer] => Array
(
[0] => https://panel.sendcloud.nl/api/v2/labels/normal_printer/1440143?start_from=0
[1] => https://panel.sendcloud.nl/api/v2/labels/normal_printer/1440143?start_from=1
[2] => https://panel.sendcloud.nl/api/v2/labels/normal_printer/1440143?start_from=2
[3] => https://panel.sendcloud.nl/api/v2/labels/normal_printer/1440143?start_from=3
)
[label_printer] => h1
)
[order_number] => ORD03
[carrier] => Array
(
[code] => dhl
)
[tracking_url] => xx
)
print_r request $orders array To big to copy and place all array, not necessary also since no other info is needed.
Array
(
[0] => Array
(
**[id] => 15817386** HERE!
I got it to work, Thanks for anyone that tried to understand me and/or help.!
for($x = 0 ; $x < 50 ; $x++){
if(($orders[$x]['paymentStatus'] == 'paid') || ($orders[$x]['paymentIsPost'] == true)){
if($orders[$x]['id'] == $parcels[$x]['data']['seoshop_order_id']){
echo '<pre>';
var_export($orders[$x]['id']);
var_export($orders[$x]['lastname']);
var_export($orders[$x]['paymentStatus']);
var_export($orders[$x]['paymentIsPost']);
var_export($parcels[$x]['name']);
var_export($parcels[$x]['data']['seoshop_order_id']);
echo '</pre>';
}
}
}
i am able to print the response from an api but it is nested array i am not able to save it.
Array
(
[statuscode] => 0
[status] => SUCCESS
[item] => SimpleXMLElement Object
(
[item] => Array
(
[0] => SimpleXMLElement Object
(
[BENEID] => 227287
[BENENAME] => test
[BANKNAME] => test
[BRANCHNAME] => test
[CITY] => test
[STATE] => tetst
[IFSCCODE] => HBNB
[ACCOUNTNO] => 4545345
[MMID] => SimpleXMLElement Object
(
[0] =>
)
[MOBILE] => 0
[BENESTATUS] => Approved
[MMIDSTATUS] => 0
[IFSCSTATUS] => 1
[IMPSMMIDENABLE] => 0
[IMPSIFSCENABLE] => 0
[IMPSNEFTENABLE] => 1
[DELETESTATUS] => 0
)
)
)
)
This is the response i am getting i want to print all fields separately
This very simple just follow the structure of response which you are getting from API
Try this:-
I suppose your repsonse in a array $reponseArray
foreach($reponseArray['item']->item as $value)
{
foreach($value as $key=>$val)
{
echo $key.' = '. $val;
}
}
How would i get the value of a key in an array?
The array is done by google shopping api which is:
// Valid source values are "public", "cx:cse", and "gan:pid"
// See http://code.google.com/apis/shopping/search/v1/getting_started.html#products-feed
$source = "public";
// For more information about full text search with the shopping API, please
// see http://code.google.com/apis/shopping/search/v1/getting_started.html#text-search
$query = "\"mp3 player\" | ipod";
//The order in which the API returns products is defined by a ranking criterion.
// See http://code.google.com/apis/shopping/search/v1/getting_started.html#ranking
$ranking = "relevancy";
$results = $service->products->listProducts($source, array(
"country" => "UK",
"q" => $query,
"rankBy" => $ranking,
));
print "<h1>Shopping Results</h1><pre>" . print_r($results, true) . "</pre>";
I have the following array which outputs:
Shopping Results
Array
(
[kind] => shopping#products
[etag] => "*********"
[id] => tag:google.com,2010:shopping/products
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products?country=UK&q=iphone&rankBy=relevancy
[nextLink] => https://www.googleapis.com/shopping/search/v1/public/products?country=UK&q=iphone&rankBy=relevancy&startIndex=26
[totalItems] => 771622
[startIndex] => 1
[itemsPerPage] => 25
[currentItemCount] => 25
[requestId] => 0CMjH976CqbECFYNWtAodLRwAAA
[items] => Array
(
[0] => Array
(
[kind] => shopping#product
[id] => tag:google.com,2010:shopping/products/5735617/11254757413841304510
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products/5735617/gid/11254757413841304510
[product] => Array
(
[googleId] => 11254757413841304510
[author] => Array
(
[name] => Amazon.co.uk
[accountId] => 5735617
)
[creationTime] => 2012-05-04T05:03:50.000Z
[modificationTime] => 2012-07-20T02:02:16.000Z
[country] => GB
[language] => en
[title] => Apple iPod touch 8GB - Black - 4th Generation (Latest Model - Launched Sept 2010)
[description] => Apple iPod touch 8GB - Black - 4th Generation (Latest Model - Launched Sept 2010)
[link] => http://www.amazon.co.uk/dp/B0040GIZTI/ref=asc_df_B0040GIZTI8843997?smid=A1YZ4RXO7GUOYN&tag=googlecouk06-21&linkCode=asn&creative=22218&creativeASIN=B0040GIZTI
[brand] => Apple
[condition] => new
[gtin] => 00885909394739
[gtins] => Array
(
[0] => 00885909394739
)
[mpns] => Array
(
[0] => MC540BT/A
)
[inventories] => Array
(
[0] => Array
(
[channel] => online
[availability] => inStock
[price] => 135.95
[shipping] => 1.99
[currency] => GBP
)
)
[images] => Array
(
[0] => Array
(
[link] => http://ecx.images-amazon.com/images/I/41p2rNmazRL.jpg
[status] => available
)
)
)
)
[1] => Array
(
[kind] => shopping#product
[id] => tag:google.com,2010:shopping/products/5735617/4597224105326146239
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products/5735617/gid/4597224105326146239
[product] => Array
(
[googleId] => 4597224105326146239
[author] => Array
(
[name] => Amazon.co.uk
[accountId] => 5735617
)
[creationTime] => 2012-05-04T05:03:50.000Z
[modificationTime] => 2012-07-20T02:02:16.000Z
[country] => GB
[language] => en
[title] => SanDisk Sansa Clip+ 8GB MP3 Player with Radio and Expandable MicroSD/SDHC Slot - Black
[description] => 8 GB memory Digital FM-tuner with 40 preset radio stations Extendable microSD/microSDHC card slot
[link] => http://www.amazon.co.uk/dp/B002NX0ME6/ref=asc_df_B002NX0ME68843997?smid=A3P5ROKL5A1OLE&tag=googlecouk06-21&linkCode=asn&creative=22206&creativeASIN=B002NX0ME6
[brand] => SanDisk
[condition] => new
[gtin] => 00619659059989
[gtins] => Array
(
[0] => 00619659059989
)
[mpns] => Array
(
[0] => SDMX18-008G-E46K
)
[inventories] => Array
(
[0] => Array
(
[channel] => online
[availability] => inStock
[price] => 46.95
[shipping] => 0
[currency] => GBP
)
)
[images] => Array
(
[0] => Array
(
[link] => http://ecx.images-amazon.com/images/I/419U6bYDF1L.jpg
[status] => available
)
)
)
)
I don't need all this data i just need 3-4 of the keys but how would i access them? How would i echo the value of say [title] from each array?
This should work:
foreach( $results as $result)
foreach( $result['product'] as $product)
echo $product['title'];
You could either loop through the array like pointed out above or possibly use array_walk_recursive like this:
$title_array = array();
array_walk_recursive($input_array, 'find_titles');
function find_titles($value, $key) {
global $title_array;
if ($key == 'title') {
$title_array[] = $value;
}
}
This might be a better solution if you you are not certain what the structure of the input array will be (i.e. how many levels deep the key you are looking for is nested).
To output the title of each product in $results:
foreach ($results as $result) {
echo $result['product']['title'];
}
Consider using array_walk_recursive
Working example
<?php
$a = array("hai", array("ha"=>1, "hai"=>2, array("a"=>1, "b"=>2)));
function test($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($a, 'test');
0 holds hai
ha holds 1
hai holds 2
a holds 1
b holds 2
If you are interested only in title
Consider using foreach
foreach($results['item'] as $result) {
echo $result['product']['title'];
}
I am attempting to use a foreach to output the array below. I have created this array via array_push() based on preg_match if/else.
Array (
[0] => Array (
[date] =>
[clickurl] => some data
[url] => some data
[dispurl] => some Data...
[title] => Transformers: Revenge of the Fallen : Reviews
[abstract] => "Transformers: Revenge of the Fallen" is a horrible experience of unbearable length, briefly punctuated by three or four amusing moments.
)
[1] => Array (
[date] =>
[clickurl] => some data
[url] => some data
[dispurl] => some Data...
[title] => Transformers : Reviews
[abstract] => After a string of bad-to-mediocre films, director Michael Bay scores with blockbuster battling robots in "Transformers."
)
)
When attempting to output the array:
foreach ($reviewArr as $review) {
echo($review['clickurl']. '<br/><br/>');
}
The output is "A" which is the first letter of Array at the start of the array above. This is the same result as using $review[0];
When using:
foreach ($reviewArr as $review) {
echo($review. '<br/><br/>');
}
the output is:
Array (
[date] =>
[clickurl] => some data
[url] => some data
[dispurl] => some data...
[title] => Transformers : Reviews
[abstract] => After a string of bad-to-mediocre films, director Michael Bay scores with blockbuster battling robots in "Transformers."
)
I am not sure why this is happening. Any help will be greatly appreciated.
thanks!
UPDATE =
This is the original Array that I parse below to split into two different arrays.
Array
(
[bossresponse] => Array
(
[responsecode] => 200
[web] => Array
(
[start] => 0
[count] => 14
[totalresults] => 14
[results] => Array
(
[0] => Array
(
[date] =>
[clickurl] => http://url.com/1
[url] => http://url.com/1
[dispurl] => http://url.com/1...
[title] => Title of Content 1
[abstract] => This is the summary, This is the summary, This is the summary, ...
)
[1] => Array
(
[date] =>
[clickurl] => http://url.com/2
[url] => http://url.com/2
[dispurl] => http://url.com/2...
[title] => Title of Content 2
[abstract] => This is the summary, This is the summary, This is the summary, ...
)
)
)
)
)
This is how I am setting the $reviewArr[].
foreach ($results['bossresponse']['web']['results'] as $key => $result) {
$url = $result['clickurl'];
$title = $result['title'];
$abstract = $result['abstract'];
$resultItem = print_r($results['bossresponse']['web']['results'][$key], true);
if (preg_match ("/reviews/i", "$url")) {
array_push($reviewArr, "$resultItem");
} else {
array_push($resultsArr, "$resultItem");
}
}
UPDATE #2 -
I see thanks to #fabio that I am simply setting a string with $resultItem above. How can I achieve creating a multidimensional array? How can I build this as an array - all of my attempts returned errors, or a string.
Array
(
[0] => Array
(
[date] =>
[clickurl] => http://url.com/1
[url] => http://url.com/1
[dispurl] => http://url.com/1...
[title] => Title of Content 1
[abstract] => This is the summary, This is the summary, This is the summary, ...
)
[1] => Array
(
[date] =>
[clickurl] => http://url.com/2
[url] => http://url.com/2
[dispurl] => http://url.com/2...
[title] => Title of Content 2
[abstract] => This is the summary, This is the summary, This is the summary, ...
)
)
Change:
foreach ($results['bossresponse']['web']['results'] as $key => $result) {
$url = $result['clickurl'];
$title = $result['title'];
$abstract = $result['abstract'];
$resultItem = print_r($results['bossresponse']['web']['results'][$key], true);
if (preg_match ("/reviews/i", "$url")) {
array_push($reviewArr, "$resultItem");
} else {
array_push($resultsArr, "$resultItem");
}
}
to:
foreach ($results['bossresponse']['web']['results'] as $key => $result) {
if (preg_match ("/reviews/i", $result['clickurl'])) {
$reviewArr[] = $result;
} else {
$resultsArr[] = $result;
}
}
I don't know how you are pushing items on your array, but I think this could do the trick:
foreach ($reviewArr as $index=>$review) {
echo($review['clickurl']. '<br/><br/>');
}
For what weird reason are you filling the array with the return value of print_r???
// this will return a string
$resultItem = print_r($results['bossresponse']['web']['results'][$key], true);
So here is the reason of your behaviour: you're printing the first character of the print_r return value which is the string representation of $results[...][...] array.
Try it by yourself
$foo = "Hello world";
echo $foo[0]; // output H
P.S. echo($review. '<br/><br/>'); will output the whole string which is the print_r output.