2

I have the following xml code in my xml:

<features>
<pool type="inground">yes</pool>
<heating type="other"/>
</features>

However, if I do a print_r on my simplexml after parsing the xml, the pool element is set up like a string instead of the heating element which is an object. i.e

[pool] => yes
[heating] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [type] => other
                )

        )

And so the following code to get the type of the pool:

$type = $pool->attributes()->type

fails giving a fatal error -> member method on non object.

What's the solution here?

Thanks in advance.

1

3 Answers 3

1

If you're looking to access the attributes of the pool tag, you need to descend to it first:

$s = '  <features>
    <pool type="inground">yes</pool>
    <heating type="other"/>
    </features>
';
$pool = simplexml_load_string($s);
var_dump($pool->pool->attributes()->type);

That seems to work; it returns this for me:

object(SimpleXMLElement)#3 (1) {
  [0]=>
  string(8) "inground"
}
Sign up to request clarification or add additional context in comments.

2 Comments

i'd use this if it was an isolated case, but my xml is full of tags like this, i really don't want to manually do this on every tag of my xml...
Would this work if Pool was setup like <pool type='inground' /> too?
1

If you want to use current reading style. You have to use as bellow

$xmlLoad = file_get_contents($XML_FILE);
$xml = new SimpleXMLElement($xmlLoad);
echo $xml->features->heating->attributes()->type;

Comments

0

try this ?

foreach ($pool->children() as $child)
{
  $type = (string) $child->attributes()->type;
}

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.