Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/252.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在顶部插入XML节点_Php_Xml - Fatal编程技术网

Php 在顶部插入XML节点

Php 在顶部插入XML节点,php,xml,Php,Xml,我试图弄清楚如何让xml节点插入(insertBefore)到顶部,而不是之后。例如:image1、image2、image3 <data> <image src="image3" /> <-- Notice <image src="image2" /> <-- Notice <image src="image1" /> </data> $dom = new

我试图弄清楚如何让xml节点插入(insertBefore)到顶部,而不是之后。例如:image1、image2、image3

   <data>
   <image src="image3" />  <-- Notice 
   <image src="image2" />  <-- Notice 
   <image src="image1" />
   </data>        



    $dom = new DOMDocument();
    $dom->formatOutput = true;

    $dom->load('myfile.xml');

    $root = $dom->documentElement;
    $newresult = $root->appendChild( $dom->createElement('image') );

    $newresult->setAttribute('id', '10');
    $newresult->setAttribute('src', pic.jpg');
    $newresult->setAttribute('desc', 'Timothy');

    //echo ''. $dom->saveXML() .'';
    $dom->save('myfile.xml') or die('XML Manipulate Error');

加载('myfile.xml');
$root=$dom->documentElement;
$newresult=$root->appendChild($dom->createElement('image'));
$newresult->setAttribute('id','10');
$newresult->setAttribute('src',pic.jpg');
$newresult->setAttribute('desc','Timothy');
//回显“”$dom->saveXML();
$dom->save('myfile.xml')或die('xml操作错误');


谢谢!如果您能给我任何帮助,我将不胜感激

您希望使用
insertBefore()
而不是
appendChild()

更换

$newresult = $root->appendChild( $dom->createElement('image') );

$newresult = $root->insertBefore($dom->createElement('image'), $root->firstChild);
更改的代码表示在
数据
元素的第一个子元素之前插入新的
图像
元素。即使
数据
元素没有子元素,这仍然有效


.

太好了!我离得太近了!非常感谢你!