dsztc99732 2010-01-02 04:02
浏览 52
已采纳

从SimpleXMLElement对象获取项目

From what I can tell, a SimpleXMLElement is just an array of other SimpleXMLElements, plus some regular array values if there wasn't a tag nested in another tag.

I have a SimpleXMLElement in a variable $data, and var_dump($data) gives me this:

object(SimpleXMLElement)#1 (33) {
  ["buyer-accepts-marketing"]=>
  string(4) "true"
...
...

but calling var_dump($data->buyer-accepts-marketing) gives me an error, and var_dump($data["buyer-accepts-marketing"]) gives me NULL. Calling var_dump($data->shipping-address->children()) gives me an error.

going like this:

foreach($data as $item) {
    var_dump($item);
}

gives a whole bunch of SimpleXMLElement objects, but oddly enough, no strings or ints.

What am I missing here? I want to take specific portions of it and pass them to a function, so for example, I don't have to go

$data->billing-address->postal-code;

...

$data->shipping-address->postal-code;

...

and can just go

address($data->billing-address);
address($data->shipping-address);

etc.

  • 写回答

1条回答 默认 最新

  • doucan9079 2010-01-02 04:08
    关注

    SimpleXMLElement is not just an array. To access child elements, you must use object notation ($a->b) and to access attributes you must use array notation ($a['b']).

    Problem is, with object notation, valid tag names can be illegal PHP code.

    You need to do this:

    $data->{'buyer-accepts-marketing'};
    

    Note that this returns a SimpleXMLElement! The reason for this is that it can contain either just text, more child elements, or both. The output of var_dump() is very misleading for SimpleXMLElements. If you want to the text content of a single <buyer-accepts-marketing> tag, you have to do this:

    (string)$data->{'buyer-accepts-marketing'};
    

    Of course it is also perfectly legal to do this:

    (int)$data->{'buyer-accepts-marketing'};
    

    The reason this appears to work in some cases (such as echoing a SimpleXMLElement) is that the type conversions are implicit and automatic. You can't echo an object, so PHP automatically converts it to a string.

    I have a love/hate relationship with SimpleXML. It makes things very easy only after you understand how complex the actual API is.

    Read up on the so-called "basic" examples to get a good handle on it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 蓝桥oj3931,请问我错在哪里
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染