简体   繁体   English

PHP SimpleXMLElement转换错误?

[英]PHP SimpleXMLElement convert bug?

I am using SimpleXMLElement to help me to create a object from string, but facing some problem : 我正在使用SimpleXMLElement来帮助我从字符串创建对象,但是遇到了一些问题:

If the xml string just have one info tag that will convert the element belongs info to object 如果xml字符串只有一个info标签,该标签会将元素所属的info转换为object

<?xml version='1.0' encoding='utf-8'?>
<string>
    <TotalRecords>1</TotalRecords>
    <data>
        <info>
            <name>huge</name>
            <age>27</age>
        </info>
    </data>
</string>

if the xml string have multiple info tag that will convert the element belogs info to array 如果xml字符串具有多个info标记,该标记会将元素belogs info转换为array

<?xml version='1.0' encoding='utf-8'?>
<string>
    <TotalRecords>1</TotalRecords>
    <data>
        <info>
            <name>huge</name>
            <age>27</age>
        </info>
        <info>
            <name>alex</name>
            <age>27</age>
        </info>
    </data>
</string>

Is that can be fix all situation to array ? 那可以解决所有情况到array吗? or have another php method to convert more perfectly? 或有另一个PHP方法来更完美地转换?

在此处输入图片说明

SimpleXML never converts anything into an array, you have just been misled by the output of your debug function. SimpleXML从不将任何内容转换为数组,您只是被调试功能的输出所迷惑。

In fact, SimpleXML is incredibly helpful in this situation, and lets you choose whether to: 实际上,SimpleXML在这种情况下非常有用,可以让您选择是否:

  • access the first <info> element and ignore any others (eg $name = (string)$xml->data->info->name; ) 访问第一个<info>元素,并忽略其他任何元素(例如$name = (string)$xml->data->info->name;
  • access a particular element with the same name by numeric index (eg $first_name = (string)$xml->data->info[0]->name; $second_name = (string)$xml->data->info[1]->name; ) 通过数字索引访问具有相同名称的特定元素(例如$first_name = (string)$xml->data->info[0]->name; $second_name = (string)$xml->data->info[1]->name;
  • loop over all elements with the same name, even if there's only one (eg foreach ( $xml->data->info as $info ) { $this_name = (string)$info->name; } ) 循环遍历所有具有相同名称的元素,即使只有一个(例如foreach ( $xml->data->info as $info ) { $this_name = (string)$info->name; }
  • loop over all elements at a particular level regardless of name (eg $info = $xml->data->info[0]; foreach ( $info->children() as $tag_name => $element ) { echo "$tag_name = ", (string)$element; } 循环遍历特定级别的所有元素,而不管其名称如何(例如$info = $xml->data->info[0]; foreach ( $info->children() as $tag_name => $element ) { echo "$tag_name = ", (string)$element; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM