使用PHP添加,更新和编辑XML文件 [英] Add, update and edit an XML file with PHP

查看:91
本文介绍了使用PHP添加,更新和编辑XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个xml文件,我想创建一个表单/表来使用PHP添加,编辑和删除记录.目前,我使用simpleXML加载XML文件,并将其内容显示在各个页面上.

I have an xml file which I would like to create a form/table around to add, edit and delete records using PHP. Currently I use simpleXML to load the XML file, and display its content on various pages.

有什么方法可以创建一个显示所有结果的表,并允许我编辑或删除表中代表XML文件中完整记录的特定行.

Is there any way I can create a table that shows all results, and allows me to either edit or delete that particular row of the table which represents a full record within the XML file.

单击编辑"时,我希望记录中的详细信息以用户可以更改然后保存并保存的形式显示,从而更新XML文件和相应的网页.

When clicking edit I would like the details from the record to appear in a form which the user can change and then save out, updating the XML file and the corresponding web page.

我需要在PHP中完成此操作,最好使用SimpleXML,尽管建议使用PHP进行其他操作.

I need this done in PHP, preferably using SimpleXML, though open to suggestions of other ways to do this with PHP.

欢呼

推荐答案

XSLT是您的朋友,可以将XML数据库文件转换为要在网页上显示的格式.您创建一个XSL模板,该模板包含每个记录所需的所有HTML,然后使用for-each语句遍历XML文件.我将进行粗略的概述,并在需要时提供更多详细信息.

XSLT is your friend for converting the XML database file to the format you want to display on the web-page. You create an XSL template that includes all the HTML you want for each record and then iterate through the XML file with a for-each statement. I'll give a rough overview and can help with more details if needed.

这是我用来通过AJAX进行XSLT(使用XSL文件处理XML文件)的通用PHP文件.设置此代码可与浏览器在GET调用中传递的必需(和可选,如果需要)输入一起使用. p#n和p#v(请参见下面的代码顶部的注释)是在要使用某些输入参数影响输出的情况下将传递到XSL文档中的参数和值对.在这种情况下,输出将回显到浏览器.这是通过XML和XSLT转换运行XML数据库以为您的Web显示(表或XSL文件模板中放置的内容)创建HTML的PHP​​:

Here's the generic PHP file I use to do XSLT (process an XML file with an XSL file) via AJAX. This one is setup to work with required (and optional, if desired) inputs passed in a GET call from the browser. p#n and p#v (see comments at top of code below) are parameter and value pairs to be passed into the XSL document in cases where you want to use some input parameter to affect the output. In this case output is echoed back to the browser. Here's the PHP to run the XML database through and XSLT transformation to create the HTML for your web display (table, or whatever you put in the XSL file template):

<?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项):

Below is an example of an XSL file template taking an XML database document and converting it to HTML for insertion in a web page. Note the HTML span tags. All the xsl tags are processing instructions that determines what goes in and around the HTML tags in the template. In this case, we are filtering results and choosing appropriate data to display based on input parameters passed into the XSL file (see xsl:param items at near top):

<?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表达式.

Note that all the xsl tests are XPath expressions.

要删除一行,您可以在该行上有一个按钮,该按钮使用"this"参数调用JavaScript函数(请参见上面的代码中的onClick ='remProdLink(this)')以引用该行,然后获取唯一的JavaScript中行的标识符,如下所示:

To delete a row you can have a button on that row that calls a JavaScript function with the "this" argument (see onClick='remProdLink(this)' in code above) to reference the row, and then grab the unique identifier of the row in JavaScript something like this:

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查找节点,然后将其删除,如下所示:

On the server end, your PHP receives the AJAX POST with the unique identifier, loads the XML database file into simpleXml, finds the node via XPath, and removes it, something like this:

<?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中编辑该记录的一部分,也可以删除它,然后创建并追加新版本的记录.

As for editing an item, you can have another JavaScript function called similarly to the one for deleting as noted above, create a form under that item on the web page with a save changes button, and when that button is pressed call another JavaScript function to AJAX POST to the server, again similarly to deleting. Only this time your POST will need to include all the information that could have been edited in the record along with the record's unique ID. PHP file will find the appropriate record (same as for deleting), and then you can either edit parts of that record in PHP, or just remove it and the create and append the new version of the record.

我不确定您需要多少细节.希望这可以给您一个良好的开端.如果您需要更多答案,请对我的答案发表评论.祝你好运!

I'm not sure how many details you need. Hopefully this gives you a good start. Please comment on my answer if you need more details on any part of it. Good luck!

这篇关于使用PHP添加,更新和编辑XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆