在文件顶部添加xml节点或反转循环

时间:2013-05-16 08:43:05

标签: php xml foreach nodes

我正在使用xml。读取xml文档工作正常,添加节点工作正常但我希望节点添加到xml文件之上。这可能还是这个nogo?

我想要这个的原因是因为当我显示xml文件时,我希望最后添加的节点显示为最新节点。

我用这个循环显示xml:

foreach($xml->xpath("//user[@id='12345678']") as $user){
        foreach($user->children() as $action => $data){
          echo"<li>";   
          echo $data->content;
          echo $data->date;
           echo"</li>"; 
        }
   }

如果有办法扭转循环或其他方式我很好,那就不必在顶部添加第一个节点。下面是我添加节点和xml文件结构的文件。

有没有人知道如何解决这个问题?

addxml.php

<?php
$file = "actielijst.xml";
$fp = fopen($file, "rb") or die("cannot open file");
$str = fread($fp, filesize($file));

$xml = new DOMDocument();
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->loadXML($str) or die("Error");

// get document element
echo "<xmp>OLD:\n". $xml->saveXML() ."</xmp>";

$root   = $xml->documentElement;

$content     = $xml->createElement("content");
$contentText = $xml->createTextNode("Nieuwe Factuur Mei");
$content->appendChild($contentText);

$date     = $xml->createElement("date");
$dateText = $xml->createTextNode("23-12-2010");
$date->appendChild($dateText);

$action   = $xml->createElement("action");
$action->appendChild($date);
$action->appendChild($content);

$root->appendChild($action);

$xml->save("actielijst.xml") or die("Error");

?>

actielijst.xml

<?xml version="1.0"?>
   <userid>
      ------->  Insert new action here <------
      <action>
         <date>23-01-2010</date>
         <content>nieuwe factuur</content>
      </action>
      <action>
         <date>23-01-2010</date>
         <content>karten op 01-02</content>
      </action>
    </userid>

2 个答案:

答案 0 :(得分:1)

您可以使用xpath捕获每个父节点(在您的情况下为操作),然后反转数组...

$users_arr = array_reverse($xml->xpath("action"));

现在你可以遍历这个数组了!

答案 1 :(得分:0)

这将有助于

<?php

$file = "actielijst.xml";

$fp = fopen($file, "rb") or die("cannot open file");

$str = fread($fp, filesize($file));

$xml  = simplexml_load_string($str);

$action = $xml->addChild('action');

$action->addChild('content','sundar');

$action->addChild('date','23-12-2010');

header('content-type: application/xml');

echo $xml->saveXML();