0

I'm trying to compare an element in XML with a variable using simpleXML, but I can't get it right. This is what i have so far:

PHP

$xml = simplexml_load_file('0.xml');

    if((string)$xml->stickers->sticker->id == $id) {  //<-- THIS LINE
        //code to be executed
    }

XML

<stickers>
    <sticker>
        <id>1</id>
        <content>StickerContent</content>
    </sticker>
</stickers>

This leaves me with the Notice:Trying to get property of non-object on the line i marked and i don't know how to fix it.

var_dump($xml)

object(SimpleXMLElement)#1 (1) {
  ["sticker"]=>
  array(2) {
    [0]=>
    object(SimpleXMLElement)#2 (5) {
      ["id"]=>
      string(1) "1"
      ["content"]=>
      string(1) "p"
    }
  }
}

1 Answer 1

2

It should be like this:

if ((string) $xml->sticker->id == $id)

Though if you have multiple sticker elements it would be:

if ((string) $xml->sticker[0]->id == $id)
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for your answer. I tried it, but i still get the same error.
Is $xml = simplexml_load_file('0.xml'); even getting any results? Update your post with the contents using var_dump($xml);.
@alex since stickers is the root node wouldnt it be $xml->sticker[0]->id
Yeah just testing and thats the case.
That works. Thank you! Sorry i didn't clarify that i had multiple sticker elements.

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.