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 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档
  • ¥15 字符串比较代码的漏洞
  • ¥15 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?