PHP 使用SimpleXMLElement的addChild方法添加另一个SimpleXMLElement对象的时候老是取不到完整的对象。原本参考了网上的例子以为可以直接添加,示例代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php $orders = new SimpleXMLElement( '<?xml version="1.0" encoding="UTF-8"?><orders></orders> ' ); for ( $i =1; $i <=5; $i ++){ $order = new SimpleXMLElement( '<?xml version="1.0" encoding="UTF-8"?><order></order> ' ); $item = $order ->addChild( 'item' ); $item ->addChild( 'id' , $i ); $item ->addChild( 'name' , 'shoes' ); $item ->addChild( 'price' , '110.00' ); //echo $order->asXML(); $orders ->addChild( $order ->getName(), $order ); //$orders->{$order->getName()}[]=$order; } echo $orders ->asXML(); |
发现$orders中的order子元素总是为空,不会包含item项等,但是在循环中调试打印出$order却又是完整。后来找到了这个,据说是因为SimpleXMLElement没有对要添加的对象做深复制,解决方法之一便是借助DOM。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php function sxml_append(SimpleXMLElement $to , SimpleXMLElement $from ) { $toDom = dom_import_simplexml( $to ); $fromDom = dom_import_simplexml( $from ); $toDom ->appendChild( $toDom ->ownerDocument->importNode( $fromDom , true)); } header( "Content-type: text/xml" ); $orders = new SimpleXMLElement( '<?xml version="1.0" encoding="UTF-8"?><orders></orders> ' ); for ( $i =1; $i <=5; $i ++){ $order = new SimpleXMLElement( '<?xml version="1.0" encoding="UTF-8"?><order></order> ' ); $item = $order ->addChild( 'item' ); $item ->addChild( 'id' , $i ); $item ->addChild( 'name' , 'shoes' ); $item ->addChild( 'price' , '110.00' ); sxml_append( $orders , $order ); } echo $orders ->asXML(); |
以上代码需要安装DOM扩展,其他的方法都是循环将子SimpleXMLElement的子元素取出逐一添加,而实际上$order这个xml对象是从其他对象中获取的,上面的方法就方便多了。
参考链接:
PHP – SimpleXML – AddChild with another SimpleXMLElement
PHP克隆
PHP对象和引用
PHP对象和复制