Reputation: 198
I try to import an XML file:
<works_list>
<licenses>
<name>First Company Name</name>
<work_address_list>
<address_place>
<address>36234020,first address </address>
<works>
<work>Service 1</work>
<work>Service 2</work>
<work>Service 3</work>
</works>
</address_place>
<address_place>
<address>36234020,second address</address>
<works>
<work>Service 1</work>
<work>Service 3</work>
</works>
</address_place>
</work_address_list>
</licenses>
<licenses>
...
</licenses>
</works_list>
and I want to put it in array:
$companyName = [
[
'address' => '36234020,first address',
'works' => ['Service 1', 'Service2', 'Service3']
],
[
'address' => '36234020,second address',
'works' => ['Service 1', 'Service3']
]
]
With this code
$node = simplexml_import_dom($doc->importNode($reader->expand(), true));
$companyName = (string) $node->name;
foreach ($node->work_address_list as $item) {
var_dump($item);
}
I get all elements in var_dump
:
object(SimpleXMLElement)#29 (1) { ["address_place"]=> array(2) { [0]=> object(SimpleXMLElement)#30 (7) { ["address"]=> string(142) "36234020,first address" ["works"]=> object(SimpleXMLElement)#32 (1) { ["work"]=> array(3) { [0]=> string(121) "Service 1" [1]=> string(117) "Service 2" [2]=> string(117) "Service 3" } } } [1]=> object(SimpleXMLElement)#31 (7) { ["address"]=>'..'..}
How can I access all elements and put it in array?
I thought that $company_places[] = $item->address_place;
will create two arrays but it doesn't work.
Upvotes: 1
Views: 280
Reputation: 3620
You can use simplexml_load_file
if you're trying to read from an XML file. Then use json_encode
and json_decode
respectively.
<?php
$xml = simplexml_load_file('filename.xml');
$json = json_encode($xml);
$array = json_decode($json, true);
print_r($array);
Output:
Array
(
[licenses] => Array
(
[name] => First Company Name
[work_address_list] => Array
(
[address_place] => Array
(
[0] => Array
(
[address] => 36234020,first address
[works] => Array
(
[work] => Array
(
[0] => Service 1
[1] => Service 2
[2] => Service 3
)
)
)
[1] => Array
(
[address] => 36234020,second address
[works] => Array
(
[work] => Array
(
[0] => Service 1
[1] => Service 3
)
)
)
)
)
)
)
Upvotes: 1