簡體   English   中英

在文件頂部添加xml節點或反轉循環

[英]Adding xml node on top of file or reverse the loop

我正在使用xml。 讀取xml文檔工作正常,添加節點工作正常,但是我希望節點添加到xml文件的頂部。 這可能嗎?

我想要這個的原因是因為當我顯示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>

您可以使用xpath捕獲每個父節點(針對您的情況),然后反轉數組...

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

現在您可以遍歷此數組!

這會有所幫助

<?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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM