Reputation: 25
I try to extract data from an json array but always i got empty string.
My XML:
<?xml version="1.0" encoding="UTF-8"?>
<ItemList>
<Entry Item = "test1" Object = "1tset" />
<Entry Item = "test2" Object = "2tset" />
</ItemList>
My Dump from XML:
array(1) { ["Entry"]=> array(2)
{ [0]=> array(1) { ["@attributes"]=> array(2) { ["Item"]=> string(5) "test1" ["Object"]=> string(5) "1tset" } }
[1]=> array(1) { ["@attributes"]=> array(2) { ["Item"]=> string(5) "test2" ["Object"]=> string(5) "2tset" } } } }
My php code:
$xmlString = "my.xml";
$xmlObject = simplexml_load_file($xmlString);
$xmltovar = json_decode(json_encode($xmlObject), true);
foreach($xmltovar['Entry'] as $test) {
echo $test['Item']."<br>";
}
I need to get all "Item"or "Object" from ItemList->Entry Tag.
Upvotes: 0
Views: 267
Reputation: 41
$test['@attributes']['Item'] for Item
$test['@attributes']['Object'] for Object
Upvotes: 0
Reputation: 2135
Your php must be look like this
<?php
$xmlString = "my.xml";
$xmlObject = simplexml_load_file($xmlString);
$xmltovar = json_decode(json_encode($xmlObject), true);
foreach($xmltovar['Entry'] as $test) {
echo $test["@attributes"]['Item']."<br>";
}
?>
Upvotes: 0
Reputation: 962
After the encoding and decoding your $xmltovar
is like this:
Array
(
[Entry] => Array
(
[0] => Array
(
[@attributes] => Array
(
[Item] => test1
[Object] => 1tset
)
)
[1] => Array
(
[@attributes] => Array
(
[Item] => test2
[Object] => 2tset
)
)
)
)
So instead of:
echo $test['Item']."<br>";
write:
echo $test['@attributes']['Item']."<br>";
Same goes for Object.
Upvotes: 1