[英]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在这种情况下非常有用,可以让您选择是否:
<info>
element and ignore any others (eg $name = (string)$xml->data->info->name;
) <info>
元素,并忽略其他任何元素(例如$name = (string)$xml->data->info->name;
) $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;
) foreach ( $xml->data->info as $info ) { $this_name = (string)$info->name; }
) foreach ( $xml->data->info as $info ) { $this_name = (string)$info->name; }
) $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.