dqyat62284 2012-10-22 22:42
浏览 41
已采纳

将xml元素与变量php进行比较

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条回答 默认 最新

  • douxiangui5011 2012-10-22 22:44
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?