0

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.

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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>";
}

?>

Comments

0

$test['@attributes']['Item'] for Item

$test['@attributes']['Object'] for Object

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.