How to iterate through XML values that are a SimpleXMLElement Object - php

I have an XML stream parsed to a SimpleXMLElement Object and I am trying to iterate though the available records to use as values in a PHP page.
The parent node of [listing] currently exists twice as there are two records in the test XML (listing[0] and listing[1])
But I can not get this to work like shown on the "Basic SimpleXML usage" from the PHP Manual
<?php
$xml = simplexml_load_file('http://feed.postlets.com/Burndog/6458ec1af54f632');
This works to provide the first listing title element value:
$value1 = $xml->listing[0]->title;
echo ' here:' . $value1;
This fails to iterate through the available values:
foreach ($xml->listing->title as $title) {
echo $title;
}
?>
values from a print_r:
SimpleXMLElement Object
(
[listing] => Array
(
[0] => SimpleXMLElement Object
(
[url] => http://www.postlets.com/repb/6509636
[title] => 3BR/2BA Manufactured - Beaumont
[subtitle] => SimpleXMLElement Object
(
)
[description] => SimpleXMLElement Object
(
)
[location] => SimpleXMLElement Object
(
[street] => 1415 E 6th St
[city] => Beaumont
[zipcode] => 92223
[state] => CA
[latitude] => 33.928326
[longitude] => -116.959923
[walkscore] => 46
)
[details] => SimpleXMLElement Object
(
[money] => SimpleXMLElement Object
(
[price] => 44900
)
[property_for] => Sale
[property_use] => Residential
[property_type] => Manufactured
[year_built] => 2011
[bedrooms] => 3
[full_bathrooms] => 2
[partial_bathrooms] => 0
[sqft] => 1041
[lot_size] => 1045 sqft
[parking] => SimpleXMLElement Object
(
)
)
[photos] => SimpleXMLElement Object
(
[photo_1] => http://www.postlets.com/create/photos/20111101/082821_6509636_158803034.jpg
[photo_caption_1] => Photo 1
[photo_2] => http://www.postlets.com/create/photos/20111101/082822_6509636_3416721218.jpg
[photo_caption_2] => Photo 2
[photo_3] => http://www.postlets.com/create/photos/20111101/082822_6509636_1298858591.jpg
[photo_caption_3] => Photo 3
)
[contact] => SimpleXMLElement Object
(
)
)
[1] => SimpleXMLElement Object
(
[url] => http://www.postlets.com/repb/7066849
[title] => 2BR/1+1BA Manufactured - Beaumont
[subtitle] => SimpleXMLElement Object
(
)
[description] => SimpleXMLElement Object
(
)
[location] => SimpleXMLElement Object
(
[street] => 1415 E 6th St # 12
[city] => Beaumont
[zipcode] => 92223
[state] => CA
[latitude] => 33.929199
[longitude] => -116.959831
[walkscore] => 46
)
[details] => SimpleXMLElement Object
(
[money] => SimpleXMLElement Object
(
[price] => 56000
[hoa] => 400
)
[property_for] => Sale
[property_use] => Residential
[property_type] => Manufactured
[year_built] => 1997
[bedrooms] => 2
[full_bathrooms] => 1
[partial_bathrooms] => 1
[sqft] => 1250
[lot_size] => 3000 sqft
[property_features] => Central A/C, Dining room, Breakfast nook, Dryer
[community_features] => Covered parking
[parking] => SimpleXMLElement Object
(
)
) etc etc
Then what will it take to loop through the elements for pictures as there is more than one?
Thanks!

As you can see in your print_r output, the 'listing' field of the XML-Object is the array, not the title. So what you have to do is iterate through the listings and print out each listings title:
foreach ($xml->listing as $listing)
{
echo $listing->title;
}
To print out the pictures you'd do something like this:
foreach ($xml->listing as $listing)
{
echo "Title: " . $listing->title . "<br>";
foreach ($listing->photos->children() as $child)
{
echo $child . "<br>";
}
}

Related

get std class value from an std classin php

stdClass Object
(
[id_pro_alert] => 155
[User_Id] => 252
[Pro_Id] => 329
[alertmethod] => daily
[Alertname] => xcxv
[name] => cyriac
[email] => cyriac#tewve.com
[date] => 2016-21-10 09:20:26
[mobile] =>
[comments] =>
[Alert_Id] => 329
[Prop_Purpose] => lease
[Min_Area] => 500
[Max_Area] => 1000
[Area_unit] => Sq.ft
[Min_cost] => 1000
[Max_cost] => 10000
[City] => kochi
[Create_Date] => 2016-10-17 12:59:14
[Update_Date] => 2016-10-17 12:59:14
[Status] => Active
[0] => stdClass Object
(
[Prop_type] => Agricultural Land
)
[1] => stdClass Object
(
[Prop_type] => Office in IT park
)
[2] => stdClass Object
(
[Prop_type] => Business center
)
)
How to get Prop_type value from stdclass
Check this, You can access all Prop_type's
foreach($data as $key=>$row){
if (is_int($key)) {
echo $row->Prop_type;
}
}
Create array of Prop_type's
$propData =array();
foreach($data as $key=>$row){
if (is_int($key)) {
$propData[] = $row->Prop_type;
}
}
echo $array->0->Prop_type;

how to convert xml array to php array [duplicate]

This question already has answers here:
How to convert XML into array in PHP?
(12 answers)
Closed 7 years ago.
I am working on property site. My requirement is to import property info with its images and amenities and store it in to database. I've an xml array and i want to convert it into php array. I've xml array like this:-
SimpleXMLElement Object
(
[Listing] => Array
(
[0] => SimpleXMLElement Object
(
[count] => 1
[Ad_Type] => Rent
[Unit_Type] => Office
[Unit_Model] => SimpleXMLElement Object
(
)
[Primary_View] => SimpleXMLElement Object
(
)
[Unit_Builtup_Area] => 7593.00
[No_of_Bathroom] => 2
[Property_Title] => Business Center / BANKS offices/ Call Centre Offices
[Web_Remarks] => SimpleXMLElement Object
(
)
[Emirate] => Dubai
[Community] => Sheikh Zayed Road
[Property_Name] => Millennium Plaza
[Property_Ref_No] => AMB-R-1142
[Listing_Agent] => Janette Ceniza
[Listing_Agent_Phone] => 0564843282
[Listing_Date] => 2015-03-26 4:53:51 pm
[Last_Updated] => 2015-07-29 1:44:23 pm
[Bedrooms] => SimpleXMLElement Object
(
)
[Listing_Agent_Email] => consult1#khalidalattar.com
[Price] => 1200000
[Frequency] => per year
[Unit_Reference_No] => AMB-R-1142
[No_of_Rooms] => SimpleXMLElement Object
(
)
[Latitude] => 25.062252
[Longitude] => 55.130672
[unit_measure] => Sq.Ft.
[Featured] => 0
[Images] => SimpleXMLElement Object
(
[image] => Array
(
[0] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_54_19-1605-6d8e8f3aa6e53b45154eac91e2109ba4.jpg
[1] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_54_35-1605-660a612b520978e1249c29b7fb591b45.jpg
[2] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_54_36-1605-01d394a6a096b9a0252b30a10fd59c13.jpg
[3] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_54_38-1605-80df60708c007c5a85721b89c97836d8.jpg
[4] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_54_38-1605-1f9ffdde85af52dfc6f3548264c34ce0.jpg
[5] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_54_44-1605-322badce946a4883abe602bf8c221a93.jpg
[6] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_54_44-1605-117288432442fd54dae0e68238f39537.jpg
[7] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_54_54-1605-914e38a1abe6418ea10885b94e4f26de.jpg
[8] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_54_55-1605-fc756a57f7280678b41b07340e3d1e60.jpg
[9] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_54_55-1605-53eb6e2277f1b19ee40a36660086a20e.jpg
[10] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_58_36-1605-9e54faba2c9f96e31646c0660f3f0153.jpg
)
)
[Facilities] => SimpleXMLElement Object
(
[facility] => Array
(
[0] => Built in wardrobes
[1] => Covered parking
[2] => Public parking
)
)
[company_name] => Amber Real Estate
[Web_Tour] => SimpleXMLElement Object
(
)
[Threesixty_Tour] => SimpleXMLElement Object
(
)
[Audio_Tour] => SimpleXMLElement Object
(
)
[Virtual_Tour] => SimpleXMLElement Object
(
)
[QR_Code] => SimpleXMLElement Object
(
)
[company_logo] => http://crm.propspace.com/application/views/pictures/logos/16051408971828.png
[Parking] => 2
[Strno] => SimpleXMLElement Object
(
)
[PreviewLink] => http://crm.propspace.com/preview/index/14273740230306248/1605/?l_id=1576257622628120
)
)
)
There are multiple entries like this. I'd given first entry for the referrence. For converting this xml to php array I've written the below code:-
function convert_xml($xml){
$arr = array();
foreach($xml->children() as $property){
if(count($property->children()) == 0){
$arr[$property->getName()] = strval($property);
}else{
$arr[$property->getName()][] = xml2array($property);
}
}
return $arr;
}
$xml_Arr = convert_xml($xml);
echo "<pre>"; print_r($xml_Arr); exit;
I m getting the result as php array given below.
Array
(
[Listing] => Array
(
[0] => Array
(
[count] => 1
[Ad_Type] => Rent
[Unit_Type] => Office
[Unit_Model] =>
[Primary_View] =>
[Unit_Builtup_Area] => 7593.00
[No_of_Bathroom] => 2
[Property_Title] => Business Center / BANKS offices/ Call Centre Offices
[Emirate] => Dubai
[Community] => Sheikh Zayed Road
[Property_Name] => Millennium Plaza
[Property_Ref_No] => AMB-R-1142
[Listing_Agent] => Janette Ceniza
[Listing_Agent_Phone] => 0564843282
[Listing_Date] => 2015-03-26 4:53:51 pm
[Last_Updated] => 2015-07-29 1:44:23 pm
[Bedrooms] =>
[Listing_Agent_Email] => consult1#khalidalattar.com
[Price] => 1200000
[Frequency] => per year
[Unit_Reference_No] => AMB-R-1142
[No_of_Rooms] =>
[Latitude] => 25.062252
[Longitude] => 55.130672
[unit_measure] => Sq.Ft.
[Featured] => 0
[Images] => Array
(
[0] => Array
(
[image] => http://crm.propspace.com/watermark?c_id=1605&l_id=1576257622628120&aid=1447092&id=14273740230306248&image=26_03_2015-16_58_36-1605-9e54faba2c9f96e31646c0660f3f0153.jpg
)
)
[Facilities] => Array
(
[0] => Array
(
[facility] => Public parking
)
)
[company_name] => Amber Real Estate
[Web_Tour] =>
[Threesixty_Tour] =>
[Audio_Tour] =>
[Virtual_Tour] =>
[QR_Code] =>
[company_logo] => http://crm.propspace.com/application/views/pictures/logos/16051408971828.png
[Parking] => 2
[Strno] =>
[PreviewLink] => http://crm.propspace.com/preview/index/14273740230306248/1605/?l_id=1576257622628120
)
)
)
There are 10 element inside image array, but it is returning only the last image. I want image array as well in my result.
foreach($xml->children() as $key=>$property){
if(count($property->children()) == 0){
$arr[$property->getName()] = strval($property);
}else{
$arr[$property->getName()][$key] = xml2array($property);
}
}

Retrieve a value from a SimpleXML object

Excuse me for asking such a "noob" question, but I have been trying to find a simple example of how to loop through my returned xml for the past few hours and I'm getting no where. I just want to be able to cycle through the xml and pull the 'Amount' attribute and 'AmazonOrderId' attribute for each Order. I don't know how to loop, nor how to grab the pertinent data.
SimpleXMLElement Object
(
[ListOrdersResult] => SimpleXMLElement Object
(
[Orders] => SimpleXMLElement Object
(
[Order] => Array
(
[0] => SimpleXMLElement Object
(
[ShipmentServiceLevelCategory] => SecondDay
[OrderTotal] => SimpleXMLElement Object
(
[Amount] => 5.93
[CurrencyCode] => USD
)
[SellerOrderId] => 107-1261608-7067458
[FulfillmentChannel] => AFN
[BuyerEmail] => 5qhs64ktb88pdsj#marketplace.amazon.com
[OrderStatus] => Shipped
[BuyerName] => Derrick D Vann
[ShipServiceLevel] => SecondDay
[LastUpdateDate] => 2013-03-13T02:20:31Z
[PurchaseDate] => 2013-03-11T06:14:40Z
[NumberOfItemsUnshipped] => 0
[MarketplaceId] => ATVPDKIKX0DER
[SalesChannel] => Amazon.com
[ShippingAddress] => SimpleXMLElement Object
(
[Phone] => 202 746-2567
[PostalCode] => 20001-4040
[Name] => Derrick Vann
[CountryCode] => US
[StateOrRegion] => DC
[AddressLine1] => 2120 Vermont Ave NW Apt 117
[City] => Washington
)
[NumberOfItemsShipped] => 1
[AmazonOrderId] => 107-1261608-7067458
[PaymentMethod] => Other
)
[1] => SimpleXMLElement Object
(
[ShipmentServiceLevelCategory] => Expedited
[OrderTotal] => SimpleXMLElement Object
(
[Amount] => 23.30
[CurrencyCode] => USD
)
[SellerOrderId] => 104-9066827-4446667
[FulfillmentChannel] => AFN
[BuyerEmail] => 6kfc88nrsnm83fq#marketplace.amazon.com
[OrderStatus] => Shipped
[BuyerName] => Quoc Bui
[ShipServiceLevel] => Expedited
[LastUpdateDate] => 2013-03-13T09:34:26Z
[PurchaseDate] => 2013-03-11T08:07:13Z
[NumberOfItemsUnshipped] => 0
[MarketplaceId] => ATVPDKIKX0DER
[SalesChannel] => Amazon.com
[ShippingAddress] => SimpleXMLElement Object
(
[Phone] => (02) 9560 3639
[PostalCode] => 2204
[Name] => Quoc Minh Bui
[CountryCode] => AU
[StateOrRegion] => New South Wales
[AddressLine1] => 19 Centennial St
[City] => Marrickville
)
[NumberOfItemsShipped] => 1
[AmazonOrderId] => 104-9066827-4446667
[PaymentMethod] => Other
)
...
SimpleXML is just great, isn't it?
foreach ($xml->ListOrdersResult->Orders->Order as $order) {
$amazonOrderId = (string) $order->AmazonOrderId;
$orderTotal = (string) $order->OrderTotal->Amount;
}
I use (string) type casting because you'd get SimpleXMLElements back for those scalar values otherwise.
pull the 'Amount' attribute and 'AmazonOrderId' attribute for each Order.
If I take you word-by-word, then this is what you're looking for:
$allThoseAttributes = $xml->xpath('//Order/#Amount|//Order/#AmazonOrderId');
However, more likely you're looking for:
$orders = [];
foreach ($xml->xpath('//Order') as $order) {
$orders[] = [
'amazon' => (string) $order->AmazonOrderId
'total' => (string) $order->OrderTotal->Amount;
];
}
because what you call attributes are infact elements. If you want to learn more about XML and Xpath, this is a good read: XPath

Access part of SimpleXMLElement Object - PHP

I need to loop through the items as an array within the SimpleXMLElement Object below but cannot seem to access it using $order->order->order->items. I can access the delivery and billing addresses using the same format, ie. $order->order->order->delivery_address and expected to get to the items array in the same way. However, I get an empty SimpleXMLElement Object when I print_r($order->order->order->items)
SimpleXMLElement Object
(
[order] => SimpleXMLElement Object
(
[id] => 860268
[shopkeeper_orderno] => 1001
[customer] => 797476
[creationdate] => Apr 19 2012 10:36:38:100AM
[reference] => k2koju45rmaqfl45n20xbkmq
[net] => 1500
[vat] => 17.5
[status] => 0
[isnew] => 1
[deductions] => 0
[postage] => 1
[paymentmethod] => PayPal
[instructions] => SimpleXMLElement Object
(
)
[errors] => SimpleXMLElement Object
(
)
[kashflow_synch] => 0
[order] => Array
(
[0] => SimpleXMLElement Object
(
[billing_address] => SimpleXMLElement Object
(
[0] =>
)
)
[1] => SimpleXMLElement Object
(
[delivery_address] => SimpleXMLElement Object
(
[0] =>
)
)
[2] => SimpleXMLElement Object
(
[items] => Array
(
[0] => SimpleXMLElement Object
(
[id] => 1285158
[headerID] => 860268
[productID] => 4867690
[description] => TEST ORDERING PF NODES - Special Offer Price
[net] => 1400
[vat] => 0
[qty] => 1
[formID] => -1
)
[1] => SimpleXMLElement Object
(
[id] => 1285159
[headerID] => 860268
[productID] => 4959678
[description] => Wedding dress
[net] => 100
[vat] => 17.5
[qty] => 1
[formID] => -1
)
)
)
)
[postage_tax] => 0
[dispatched] => 0
[paybyotherid] => -1
[ip] => 81.168.43.121
[wheredidyouhearid] => -1
)
)
EDIT: I just saw you made a mistake with the naming, the parent needs to be called <orders> and the sub items <order>
The SimpleXMLElement seems to be empty, in fact it's usually filled but not displayed when dumping (whoever thought of this crazy behaviour)
Can you try this?
foreach($order->orders->order as $order) { // should be orders then
echo $item->getName();
}
Or try it with SimpleXMLElement::children()
your items are actually on the second offset of the order array.
I'd just use the xPath to process these.
foreach($xmlObject->xpath('/order/order[2]/items') as $item)
{
// Do something with my $item
}
You can use a loop like the one below, then all you need to do is $items->id
foreach($order->children()->children()->items as $items)
{
}
Using Dan Lees suggestion I tried SimpleXMLElement::children() and did the below which works
foreach ($order->children() as $order) {
foreach ($order->children() as $order_details) {
foreach ($order_details->children() as $order_items) {
echo $order_items->id;
}
}
}

Go directly to simplexmlelement without xpath php

Still very new to php...
I have a large simplexmlstring and i want to get all the lastnames from the file and in which article they where:
something like:
article number 0 author position 0 'van Tricht'
article number 0 author position 1 'Nieman'
article number 0 author position 2 'van Tricht'
article number 0 author position 3 'Bour'
.....
article number 1 author position 0 'van Tricht'
article number 1 author position 1 'Nieman'
article number 1 author position 2 'van Tricht'
article number 1 author position 3 'Bour'
I want to go directly to Author->LastName but without the use of xpath, i tried it with xpath, but then my foreach loops give strange outputs... this what i tried:
<?php
$i = 0;
$j = 0;
foreach ($xml->xpath('//AuthorList') as $AuthorList) {
$i ++;
$j = 0;
foreach ($xml->xpath('//Author') as $Author) {
$j ++;
echo $i . "articlenumber " . "author position" . $AuthorList->Author->LastName;
}
}
?>
This is the xml string:
SimpleXMLElement Object
(
[PubmedArticle] => Array
(
[0] => SimpleXMLElement Object
(
[MedlineCitation] => SimpleXMLElement Object
(
[#attributes] => Array
(
[Owner] => NLM
[Status] => In-Process
)
[PMID] => 20538400
[DateCreated] => SimpleXMLElement Object
(
[Year] => 2010
[Month] => 07
[Day] => 08
)
[Article] => SimpleXMLElement Object
(
[#attributes] => Array
(
[PubModel] => Print-Electronic
)
[Journal] => SimpleXMLElement Object
(
[ISSN] => 1090-2147
[JournalIssue] => SimpleXMLElement Object
(
[#attributes] => Array
(
[CitedMedium] => Internet
)
[Volume] => 73
[Issue] => 3
[PubDate] => SimpleXMLElement Object
(
[Year] => 2010
[Month] => Aug
)
)
[Title] => Brain and cognition
[ISOAbbreviation] => Brain Cogn
)
[ArticleTitle] => Increased saccadic rate during smooth pursuit eye movements in patients at Ultra High Risk for developing a psychosis.
[Pagination] => SimpleXMLElement Object
(
[MedlinePgn] => 215-21
)
[Abstract] => SimpleXMLElement Object
(
[AbstractText] => Abnormalities in eye tracking are consistently observed in schizophrenia patients and their relatives and have been proposed as an endophenotype of the disease. The aim of this study was to investigate the performance of patients at Ultra High Risk (UHR) for developing psychosis on a task of smooth pursuit eye movement (SPEM). Forty-six UHR patients and twenty-eight age and education matched controls were assessed with a task of SPEM and psychiatric questionnaires. Our results showed that both the corrective and non-corrective saccadic rates during pursuit were higher in the UHR group. There were however no differences in smooth pursuit gain between the two groups. The saccadic rate was related to positive UHR symptoms. Our findings indicate that abnormalities in SPEM are already present in UHR patients, prior to a first psychotic episode. These abnormalities occur only in the saccadic system.
[CopyrightInformation] => 2010 Elsevier Inc. All rights reserved.
)
[Affiliation] => Department of Psychiatry, Academic Medical Center, University of Amsterdam, The Netherlands. m.j.vantricht#amc.uva.nl
[AuthorList] => SimpleXMLElement Object
(
[#attributes] => Array
(
[CompleteYN] => Y
)
[Author] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[ValidYN] => Y
)
[LastName] => van Tricht
[ForeName] => M J
[Initials] => MJ
)
[1] => SimpleXMLElement Object
(
[#attributes] => Array
(
[ValidYN] => Y
)
[LastName] => Nieman
[ForeName] => D H
[Initials] => DH
)
[2] => SimpleXMLElement Object
(
[#attributes] => Array
(
[ValidYN] => Y
)
[LastName] => Bour
[ForeName] => L J
[Initials] => LJ
)
[3] => SimpleXMLElement Object
(
[#attributes] => Array
(
[ValidYN] => Y
)
[LastName] => Boerée
[ForeName] => T
[Initials] => T
)
[4] => SimpleXMLElement Object
(
[#attributes] => Array
(
[ValidYN] => Y
)
[LastName] => Koelman
[ForeName] => J H T M
[Initials] => JH
)
[5] => SimpleXMLElement Object
(
[#attributes] => Array
(
[ValidYN] => Y
)
[LastName] => de Haan
[ForeName] => L
[Initials] => L
)
[6] => SimpleXMLElement Object
(
[#attributes] => Array
(
[ValidYN] => Y
)
[LastName] => Linszen
[ForeName] => D H
[Initials] => DH
)
)
)
[Language] => eng
etc............
In order to get the desired output, your loop should look like:
$i = 0;
foreach ($xml->xpath('//AuthorList') as $AuthorList) {
$j = 0;
foreach ($AuthorList->Author as $Author) {
echo join(' ', array('article number', $i, 'author position', $j, $Author->LastName));
$j++;
}
$i++;
}

Categories