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);
}
}
Related
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
Below is my data get from API , I try to display the shopId, Shopname and shopcode but failed.Any one can help me solve this problem ? I am using the PHP to write the script and get API data.Below is my script to get API data.
<?php
$get = file_get_contents("http://api.meirenji.cn/api/xxxxxxxxxxx");
$json = json_decode($get);
$shop_id = $json->content->shopId;
echo "Shop ID : ".$shop_id."";
?>
Below is the data that i get from API, it have multiple array data, i nee get data shopId, Shopname,shopcode
stdClass Object
(
[status] => 0
[msg] => succes
[content] => Array
(
[0] => stdClass Object
(
[shopId] => 6674
[shopname] => SP
[shopcode] => 38862185
[type] => shop
[flag] => 1
)
[1] => stdClass Object
(
[shopId] => 6498
[shopname] => Adidas
[shopcode] => 74812597
[type] => shop
[flag] => 1
)
[2] => stdClass Object
(
[shopId] => 6498
[shopname] => Nike
[shopcode] => 98741852
[type] => shop
[flag] => 1
)
[3] => stdClass Object
(
[shopId] => 6501
[shopname] => Puma
[shopcode] => 13847915
[type] => shop
[flag] => 1
)
[4] => stdClass Object
(
[shopId] => 6509
[shopname] => Adidas NEO
[shopcode] => 26700485
[type] => shop
[flag] => 1
)
[5] => stdClass Object
(
[shopId] => 6865
[shopname] => Testing Unit
[shopcode] => 23891935
[type] => shop
[flag] => 1
)
[6] => stdClass Object
(
[shopId] => 9661
[shopname] => UNDER ARMOR
[shopcode] => 88741294
[type] => shop
[flag] => 1
)
)
)
To get shopname and shopcode from your response object, you've to loop over your content like this way using foreach(),
foreach($json->content as $key=>$row){
echo "shopname = $row->shopname and shopcode = $row->shopcode". PHP_EOL;
}
DEMO: https://3v4l.org/tWqt7
I've that xml structure retrieving from device
<packet>
<info action="fiscalmemory" fiscalmemorysize="1048576" recordsize="464" fiscal="1" uniqueno="ABC12345678" nip="123-456-78-90" maxrecordscount="2144" recordscount="7" maxreportscount="1830" reportscount="4" resetmaxcount="200" resetcount="0" taxratesprglimit="30" taxratesprg="1" currencychangeprglimit="4" currencychangeprg="0" fiscalstartdate="dd-mm-yyyy hh:dd:ss" fiscalstopdate="dd-mm-yyyy hh:dd:ss" currencyname="PLN" />
<ptu name="A" bres="Nobi">123.23</ptu>
<ptu name="B">123.23</ptu>
<ptu name="D">8</ptu>
<sale>999.23</sale>
</packet>
simpleXml does't see ptu's attributes
$array = simplexml_load_string($xml);
print_r($array);
It prints
SimpleXMLElement Object
(
[info] => SimpleXMLElement Object
(
[#attributes] => Array
(
[action] => fiscalmemory
[fiscalmemorysize] => 1048576
[recordsize] => 464
[fiscal] => 1
[uniqueno] => ABC12345678
[nip] => 123-456-78-90
[maxrecordscount] => 2144
[recordscount] => 7
[maxreportscount] => 1830
[reportscount] => 4
[resetmaxcount] => 200
[resetcount] => 0
[taxratesprglimit] => 30
[taxratesprg] => 1
[currencychangeprglimit] => 4
[currencychangeprg] => 0
[fiscalstartdate] => dd-mm-yyyy hh:dd:ss
[fiscalstopdate] => dd-mm-yyyy hh:dd:ss
[currencyname] => PLN
)
)
[ptu] => Array
(
[0] => 123.23
[1] => 123.23
[2] => 8
)
[sale] => 999.23
)
As we can see ptu doesn't contain attributes :/
I also tried parse it with recursive function because children also may contain chilren but without success :/
Could anybody point to me why SimpleXML doesn't take ptu's attributes and also share any parsing function?
Thanks in advance.
edited
As regards Nigel Ren I made that function
function parseXMLtoArray($xml){
$x = simplexml_load_string($xml);
$result = [];
function parse($xml, &$res){
$res['name'] = $xml->getName();
$res['value'] = $xml->__toString();
foreach ($xml->attributes() as $k => $v){
$res['attr'][$k] = $v->__toString();
}
foreach($xml->children() as $child){
parse($child, $res['children'][]);
}
}
parse($x, $result);
return $result;
}
$resArray = parseXMLtoArray($rawXml);
print_r($resArray);
this returns such array
Array
(
[name] => packet
[value] =>
[attr] => Array
(
[crc] => BKJFKHKD54
)
[children] => Array
(
[0] => Array
(
[name] => info
[value] =>
[attr] => Array
(
[action] => fiscalmemory
[fiscalmemorysize] => 1048576
[recordsize] => 464
[fiscal] => 1
[uniqueno] => ABC12345678
[nip] => 123-456-78-90
[maxrecordscount] => 2144
[recordscount] => 7
[maxreportscount] => 1830
[reportscount] => 4
[resetmaxcount] => 200
[resetcount] => 0
[taxratesprglimit] => 30
[taxratesprg] => 1
[currencychangeprglimit] => 4
[currencychangeprg] => 0
[fiscalstartdate] => dd-mm-yyyy hh:dd:ss
[fiscalstopdate] => dd-mm-yyyy hh:dd:ss
[currencyname] => PLN
)
)
[1] => Array
(
[name] => ptu
[value] => 123.23
[attr] => Array
(
[name] => A
)
)
[2] => Array
(
[name] => ptu
[value] => 123.23
[attr] => Array
(
[name] => B
)
)
[3] => Array
(
[name] => ptu
[value] => 8
[attr] => Array
(
[name] => D
)
)
[4] => Array
(
[name] => sale
[value] => 999.23
)
)
)
Is this correct?
Thanks again Nigel
When loading with SimpleXML, using print_r() gives only an idea of the content and doesn't have the full content. If you want to see the full content then use ->asXML()...
$array = simplexml_load_string($xml);
echo $array->asXML();
To check the attributes of <ptu> element, (this just gives the first one)...
echo $array->ptu[0]['name'];
This uses ->ptu to get the <ptu> element and takes the first one [0] and then takes the name attribute using ['name'].
I have json return string like given below. I want to extract cancellation Policy list of objects like cutoff Time and refund In Percentage. I tried using for-loop but it didn't help me. Can you please help me on extracting this.
Array (
[apiStatus] => Array ( [success] => 1 [message] => SUCCESS ) <br>
[apiAvailableBuses] => Array ( <br>
[0] => Array ( [droppingPoints] => [availableSeats] => 41 <br>[partialCancellationAllowed] => [arrivalTime] => 08:00 AM <br>
[cancellationPolicy] => [<br>
{"cutoffTime":"1","refundInPercentage":"10"},<br>
{"cutoffTime":"2","refundInPercentage":"50"},<br>
{"cutoffTime":"4","refundInPercentage":"90"}<br>
] <br>
[boardingPoints] => Array ( [0] => Array ( [time] => 09:00PM [location] => Ameerpet,|Jeans Corner 9687452130 [id] => 6 ) [1] => Array ( [time] => 09:15PM [location] => S.R Nagar,S.R Nagar [id] => 2224 ) [2] => Array ( [time] => 09:10PM [location] => Kondapur,Toyota Show room [id] => 2244 ) ) [operatorName] => Deepak Travels [departureTime] => 9:00 PM [mTicketAllowed] => [idProofRequired] => [serviceId] => 6622 [fare] => 800 [busType] => 2+1 Hi-Tech Non A/c [routeScheduleId] => 6622 [commPCT] => 0 [operatorId] => 213 [inventoryType] => 0 ) <br>
[1] => Array ( [droppingPoints] => [availableSeats] => 41 [partialCancellationAllowed] => [arrivalTime] => 07:00 AM <br>
[cancellationPolicy] => [<br>
{"cutoffTime":"1","refundInPercentage":"10"},<br>
{"cutoffTime":"2","refundInPercentage":"50"},<br>
{"cutoffTime":"4","refundInPercentage":"90"}<br>
] <br>
[boardingPoints] => Array ( [0] => Array ( [time] => 09:10PM [location] => Ameerpet,|Jeans Corner [id] => 6 ) [1] => Array ( [time] => 09:00PM [location] => S.R Nagar,S.R Nagar [id] => 2224 ) [2] => Array ( [time] => 08:30PM [location] => KUKATPALLY,JNTU [id] => 2230 ) ) [operatorName] => Dhanunjayabus [departureTime] => 9:00 PM [mTicketAllowed] => [idProofRequired] => [serviceId] => 6743 [fare] => 900 [busType] => VOLVO [routeScheduleId] => 6743 [commPCT] => 0 [operatorId] => 233 [inventoryType] => 0 )
)
)
Use a foreach() for it like so:
foreach ($your_response['apiAvailableBuses'] as $el) {
$cancellationPolicy[] = $el['cancellationPolicy'];
}
Try this:
foreach($data['apiStatus']['apiAvailableBuses'] as $item) {
foreach($item['cancellationPolicy'] as $key => $json) {
$jsonDecoded = json_decode($json, true);
// And you will have access to the data like this
// $jsonDecoded['cutoffTime'];
// $jsonDecoded['refundInPercentage'];
}
}
$response = json_decode($apiResponse);
$cancellationPolicies = [];
foreach ($response->apiAvailableBuses as $availableBus) {
$cancellationPolicies[] = $availableBus['cancellationPolicy'];
// if you want to display something you can simply do it like this;
echo $availableBus['cancellationPolicy']->cutoffTime;
}
Here is my json response:
stdClass Object ( [is_claimed] => [rating] => 4 [mobile_url] => http://m.yelp.com/biz/the-waterboy-sacramento [rating_img_url] => http://s3-media4.ak.yelpcdn.com/assets/2/www/img/c2f3dd9799a5/ico/stars/v1/stars_4.png [review_count] => 455 [name] => The Waterboy [snippet_image_url] => http://s3-media1.ak.yelpcdn.com/photo/SZyFYvQmHWSLhK96SSzwwA/ms.jpg [rating_img_url_small] => http://s3-media4.ak.yelpcdn.com/assets/2/www/img/f62a5be2f902/ico/stars/v1/stars_small_4.png [url] => http://www.yelp.com/biz/the-waterboy-sacramento [menu_date_updated] => 1387494198 [reviews] => Array ( [0] => stdClass Object ( [rating] => 5 [excerpt] => AMAZING again, went here last Thursday at 5:00pm. Greeted by friendly man, he asked if we had a reservation, I said, 'no, do we need one?' He said, I'm... [time_created] => 1395158338 [rating_image_url] => http://s3-media1.ak.yelpcdn.com/assets/2/www/img/f1def11e4e79/ico/stars/v1/stars_5.png [rating_image_small_url] => http://s3-media1.ak.yelpcdn.com/assets/2/www/img/c7623205d5cd/ico/stars/v1/stars_small_5.png [user] => stdClass Object ( [image_url] => http://s3-media1.ak.yelpcdn.com/photo/SZyFYvQmHWSLhK96SSzwwA/ms.jpg [id] => H0qUqWctz5Ms6qdeaIvjFw [name] => Lori T. ) [rating_image_large_url] => http://s3-media3.ak.yelpcdn.com/assets/2/www/img/22affc4e6c38/ico/stars/v1/stars_large_5.png [id] => bZznirkpADmW3Qcpc5u_VA ) ) [phone] => 9164989891 [snippet_text] => AMAZING again, went here last Thursday at 5:00pm. Greeted by friendly man, he asked if we had a reservation, I said, 'no, do we need one?' He said, I'm... [image_url] => http://s3-media1.ak.yelpcdn.com/bphoto/9e5sodvvP3p6_53wOqVTcg/ms.jpg [categories] => Array ( [0] => Array ( [0] => French [1] => french ) [1] => Array ( [0] => Italian [1] => italian ) ) [display_phone] => +1-916-498-9891 [rating_img_url_large] => http://s3-media2.ak.yelpcdn.com/assets/2/www/img/ccf2b76faa2c/ico/stars/v1/stars_large_4.png [menu_provider] => single_platform [id] => the-waterboy-sacramento [is_closed] => [location] => stdClass Object ( [city] => Sacramento [display_address] => Array ( [0] => 2000 Capitol Ave [1] => Midtown [2] => Sacramento, CA 95811 ) [neighborhoods] => Array ( [0] => Midtown ) [postal_code] => 95811 [country_code] => US [address] => Array ( [0] => 2000 Capitol Ave ) [state_code] => CA ) )
which I get using:
$response = json_decode($data);
print_r($response);
echo $response["rating"]; //Why this does not give json response value?
Pass true into the second parameter of json_decode to return an array (which is how you're trying to access it):
$response = json_decode($data, true); // associative array returned
print_r($response);
echo $response["rating"]; // 4
Manual
Otherwise, access the rating as a property of the object that you've got:
$response = json_decode($data);
echo $response->rating; // 4
I'm trying to use the stackoverflow API and I want to get answers of a question in a php array. So far here is my php code:
<?php
//KEY
$string = "key=my_key";
//Call stack API .$string
$stack_url = "compress.zlib://http://api.stackoverflow.com/1.1/questions";
//Get and Store API results into a variable
$result = file_get_contents($stack_url);
$jsonArray = json_decode($result);
print_r($jsonArray);
//echo($jsonArray->questions[0]->question_answers_url);
//var_dump($jsonArray);
?>
I want to store the answers of a question in an array called answers so that I can access them with a for loop.
The answer i get is :
stdClass Object
(
[total] => 2618591
[page] => 1
[pagesize] => 30
[questions] => Array
(
[0] => stdClass Object
(
[tags] => Array
(
[0] => c#
[1] => ssh
[2] => openssh
[3] => rsacryptoserviceprovider
)
[answer_count] => 1
[favorite_count] => 0
[question_timeline_url] => /questions/9164203/timeline
[question_comments_url] => /questions/9164203/comments
[question_answers_url] => /questions/9164203/answers
[question_id] => 9164203
[owner] => stdClass Object
(
[user_id] => 311966
[user_type] => registered
[display_name] => simonc
[reputation] => 301
[email_hash] => 021f3344004f0c886d715314fa02037d
)
[creation_date] => 1328548627
[last_edit_date] => 1328611688
[last_activity_date] => 1328611688
[up_vote_count] => 0
[down_vote_count] => 0
[view_count] => 25
[score] => 0
[community_owned] =>
[title] => Format of PKCS private keys
)
[1] => stdClass Object
(
[tags] => Array
(
[0] => c#
[1] => .net
[2] => combobox
)
[answer_count] => 3
[favorite_count] => 0
[question_timeline_url] => /questions/9174765/timeline
[question_comments_url] => /questions/9174765/comments
[question_answers_url] => /questions/9174765/answers
[question_id] => 9174765
[owner] => stdClass Object
(
[user_id] => 1194399
[user_type] => registered
[display_name] => Goxy
[reputation] => 1
[email_hash] => 5fc8c96b6b85c6339cb9ac4ab60cb247
)
[creation_date] => 1328611202
[last_activity_date] => 1328611686
[up_vote_count] => 0
[down_vote_count] => 0
[view_count] => 15
[score] => 0
[community_owned] =>
[title] => WPF: Bind simple List<myClass> to Combobox
)
....
Not sure exactly which property you want to extract, but I assume it's the 'question_answers_url'.
$answersArray = Array();
for($i=0;$i<count($jsonArray['questions']);$i++){
//assuming it is the 'question_answers_url' property that you want
array_push($answersArray,$jsonArray['questions'][$i]['question_answers_url']);
}
Ought to do it.