簡體   English   中英

使用PHP添加,更新和編輯XML文件

[英]Add, update and edit an XML file with PHP

我有一個xml文件,我想創建一個表單/表來使用PHP添加,編輯和刪除記錄。 當前,我使用simpleXML加載XML文件,並在各個頁面上顯示其內容。

有什么辦法可以創建一個顯示所有結果的表,並允許我編輯或刪除表中代表XML文件中完整記錄的特定行。

單擊“編輯”時,我希望記錄中的詳細信息以用戶可以更改然后保存的形式顯示,從而更新XML文件和相應的網頁。

我需要在PHP中完成此操作,最好使用SimpleXML,盡管可以建議使用PHP進行其他操作。

干杯

XSLT是您的朋友,可以將XML數據庫文件轉換為您要在網頁上顯示的格式。 您創建一個XSL模板,該模板包含每個記錄所需的所有HTML,然后使用for-each語句遍歷XML文件。 我將進行粗略的概述,並在需要時提供更多詳細信息。

這是我用來通過AJAX進行XSLT(使用XSL文件處理XML文件)的通用PHP文件。 設置此代碼可與瀏覽器在GET調用中傳遞的必需(和可選,如果需要)輸入一起使用。 p#n和p#v(請參見下面的代碼頂部的注釋)是在要使用某些輸入參數影響輸出的情況下傳遞到XSL文檔中的參數和值對。 在這種情況下,輸出將回顯到瀏覽器。 這是通過XML和XSLT轉換運行XML數據庫以為您的Web顯示(表或XSL文件模板中放置的內容)創建HTML的PHP​​:

<?php
//REQUIRED INPUTS:
// - xml: path to xml document
// - xsl: path to xsl style sheet
// - pCount: number of parameters to be passed to xslt (send zero '0' if none)
//OPTIONAL INPUTS (must have as many as specified in pCount, increment '1' in
//names below up a number for each iteration):
// - p1n: name of first parameter
// - p1v: value of first parameter

//SET Paths 
$xmlPath = $_GET['xml'];
$xslPath = $_GET['xsl'];

// Load the XML source
$xml = new DOMDocument;
$xml->load($xmlPath);

$xsl = new DOMDocument;
$xsl->load($xslPath);

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

//Set Parameter(s), if present
$xslParamCount = $_GET['pCount']; //Check number of xsl parameters specified in GET
for ($i=1; $i<=$xslParamCount; $i++){
   $xslParamName = $_GET['p'.$i.'n'];
   $xslParamValue = $_GET['p'.$i.'v'];
   $proc->setParameter( '', $xslParamName, $xslParamValue);    //Set parameters for XSLTProcessor
}

// TRANSFORM
echo $proc->transformToXML($xml);

// SET Mime Type
$mime = "application/xhtml+xml";
$charset = "iso-8859-1";
header("Content-Type: $mime;charset=$charset");
?> 

下面是一個XSL文件模板的示例,該文件采用XML數據庫文檔並將其轉換為HTML以插入網頁中。 注意HTML span標簽。 所有xsl標簽都是處理指令,用於確定模板中HTML標簽的內容。 在這種情況下,我們將過濾結果並根據傳遞到XSL文件中的輸入參數選擇合適的數據進行顯示(請參見頂部的xsl:param項目):

<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>
 <xsl:param name='testId'/>
 <!--Input options for following param: localUse, notLocalUse, nottestId, or '' (all)-->
 <xsl:param name='matchType'/>
 <xsl:template match='/'>
   <xsl:choose>
      <xsl:when test="$matchType='localUse'">
         <xsl:for-each select="//test[@id=$testId and @localUse='yes']">
            <xsl:sort select="../@id"/>
            <div><xsl:if test='../@localPrefTestId=$testId'><xsl:attribute name='class'>preferredTest</xsl:attribute></xsl:if>
               <span class='productStockCode'>
                  <xsl:if test='../@localPrefTestId=$testId'>
                     <xsl:attribute name='title'>Preferred test for this product</xsl:attribute>
                  </xsl:if>
                  <xsl:if test='../@localPrefTestId!=$testId'>
                     <xsl:attribute name='title'>Alternate (not preferred) test for this product - see note to right</xsl:attribute>
                  </xsl:if>
                  <xsl:value-of select='../@id'/>
               </span>
               <span class='productStockName'>
                  <xsl:if test='../@localPrefTestId=$testId'>
                     <xsl:attribute name='title'>Preferred test for this product</xsl:attribute>
                  </xsl:if>
                  <xsl:if test='../@localPrefTestId!=$testId'>
                     <xsl:attribute name='title'>Alternate (not preferred) test for this product - see note to right</xsl:attribute>
                  </xsl:if>
                  <xsl:value-of select='../@name'/>
               </span>
               <span class='producttestNote'>
                  <xsl:value-of select='child::localPrefNote'/>
               </span>
               <span class='productDeleteButton'>
                  <input onClick='remProdLink(this)' title='Click to remove link to this product' type='image' src='button_tiny_X_grey.bmp'></input>
               </span>
            </div>
         </xsl:for-each>
      </xsl:when>
      <xsl:otherwise>
         <p>Server Error: GET must specify matchType parameter value of 'localUse', 'notLocalUse', 'nottestId', or '' (for all)</p>
         <p>matchType received: <xsl:value-of select='$matchType'/></p>
      </xsl:otherwise>
   </xsl:choose>
 </xsl:template>
 <!--Note the output method="html" below is required for this to insert correctly into a web page; without this it may nest improperly if any divs are empty-->
 <xsl:output method="html" omit-xml-declaration="yes"/>
</xsl:stylesheet>

請注意,所有xsl測試都是XPath表達式。

要刪除行,您可以在該行上放置一個按鈕,該按鈕使用“ this”參數調用JavaScript函數(請參見上面的代碼中的onClick ='remProdLink(this)')以引用該行,然后獲取該行的唯一標識符在JavaScript中排成這樣:

function remProdLink(obj){
   //get unique id via Dom from passed in object reference
   //edit everything after "obj" below to get to the unique id in the record
   var testCode = obj.parentNode.parentNode.firstChild.nextSibling.innerHTML;
   //code to send AJAX POST to server with required information goes here
}

在服務器端,您的PHP收到帶有唯一標識符的AJAX POST,將XML數據庫文件加載到simpleXml中,通過XPath查找節點,然后將其刪除,如下所示:

<?php
   //Move url encoded post data into variables
   $testCode = $_POST['testCode']; //$testCode should be a unique id for the record

   //load xml file to edit
   $xml = simplexml_load_file('yourDatabase.xml');

   //find target node for removal with XPath
   $targets = $xml->xpath("//testCode[@id=$testCode]");

   //import simpleXml reference into Dom to do removal
   $dom2 = dom_import_simplexml($targets[0]);
   $dom2->parentNode->removeChild($dom2);

   //format xml to save indented tree (rather than one line) and save
   $dom = new DOMDocument('1.0');
   $dom->preserveWhiteSpace = false;
   $dom->formatOutput = true;
   $dom->loadXML($xml->asXML());
   $dom->save('yourDatabase.xml');
?>

至於編輯項目,您可以擁有另一個JavaScript函數,類似於上面提到的用於刪除的JavaScript函數,可以使用保存更改按鈕在網頁上的該項目下創建表單,並在按下該按鈕時調用另一個JavaScript函數以AJAX POST到服務器,再次類似於刪除。 只有這一次,您的POST才需要包括記錄中可能已經編輯的所有信息以及記錄的唯一ID。 PHP文件將找到適當的記錄(與刪除相同),然后您可以在PHP中編輯該記錄的一部分,也可以將其刪除並創建並追加新版本的記錄。

我不確定您需要多少細節。 希望這給您一個良好的開端。 如果您需要任何更多詳細信息,請評論我的答案。 祝好運!

我建議您使用DomDocument和DomXPath,而不要使用SimpleXml。 但是,總的來說,XML並不是存儲數據的最佳介質-您可能正在使用數據庫進行任何操作。 如果您需要輕松交換數據,則可以使用SQLite代替更常見的MySql。

您可以使用本機XML數據庫來促進創建,添加,更新和檢索xml文檔和節點。 過去,我成功使用過BerkeleyDBXML (現在是Oracle的一部分)。 也有一個PHP庫。

暫無
暫無

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

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