5

Does anyone know if I can force a SimpleXMLElement variable to always be an array?

<result>
    <item>
        <id>1</id>
        <name>name 1</name>
    </item>
    <item>
        <id>2</id>
        <name>name 2</name>
    </item>
</result>

When parsing the above XML through simplexml_load_string() I get the following object

SimpleXMLElement Object
(
    [item] => Array
    (
        [0] => SimpleXMLElement Object
            (
                [id] => 1
                [name] => name 1
            )
        [1] => SimpleXMLElement Object
             (
                [id] => 2
                [name] => name 2
            )
    )
)

Which is great because I can loop through "item" and get the individual objects. But when item is a single entry, like below, I get a different object structure which ruins my loop becuase I start looping through "id" and "name" instead of objects.

<result>
    <item>
        <id>1</id>
        <name>name 1</name>
    </item>
</result>

SimpleXMLElement Object
(
    [item] => SimpleXMLElement Object
    (
           [id] => 1
           [name] => name 1    
    )

)

Is there anyway to force "item" to be an array with simplexml_load_string() or by re-structuring the XML?

1 Answer 1

4

You don't need to have that as an array, a simple check will do. Like

if(is_array($xml->result->item))
{
    //loop here
}
else
{
    //only one object
}

Also, a single foreach will get the job done whether there is one element or there are multiple. For example

<?php
$string="
<result>
    <item>
        <id>1</id>
        <name>name 1</name>
    </item>

</result>";

$xml = simplexml_load_string($string);

//print_r($xml);


foreach($xml->item as $item)
{
echo $item->id."\n";
}
?>

That works perfectly fine for multiple items as well. See fiddle

Fiddle

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

2 Comments

I have that solution in some of the code already but it means I either set the single "item" into an array myself or I duplicate code in the if statment
Wow didn't know foreach would react like that with a single object. I thought foreach would at least give out a warning for trying to loop through something that wasn't an array. Thanks for your answer

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.