如何使用PHP删除XML文件中的最后10个字符,然后添加一些文本?

时间:2011-03-29 13:35:40

标签: php xml

这是我的PHP代码,它从表单中获取数据:

<?php
$itemPath         = $_REQUEST['itemPath'];
$title          = $_REQUEST['title'];
$description1    = $_REQUEST['description1'];
$description2    = $_REQUEST['description2'];
$description3    = $_REQUEST['description3'];
$price          = $_REQUEST['price'];
$note            = $_REQUEST['note'];

$xmlfile = "women.xml";
$file = fopen($xmlfile,"r+");
$handle = "</items>";
$newphrase = $file;
//rewind($handle);
$newphrase = str_replace($handle, "", $newphrase);
fwrite($file, $newphrase);
fclose($file);

$file = fopen($xmlfile,"a+");
fwrite($file, "\n<item path='women/".$itemPath.".jpg' type = 'bitmapfile'>\n");
fwrite($file, "\t<title>".$title."</title>\n");
fwrite($file, "\t<description1>".$description1."</description1>\n");
fwrite($file, "\t<description2>".$description2."</description2>\n");
fwrite($file, "\t<description3>".$description3."</description3>\n");
fwrite($file, "\t<description3>".$description3."</description3>\n");
fwrite($file, "\t<price>".$price."</price>\n");
fwrite($file, "\t<note>" . $note . "</note>\n");
fwrite($file, "</item>\n");
fwrite($file,"</items>");
fclose($file);
?>

这是XML:

<items id = "items">
<item path = "women/3.jpg"  type = "bitmapfile">
<title>No.3</title>
<description1>Flowers</description1>
<description2>50 ml</description2>
<description3>pure</description3>
<price>35</price>
<note></note>
</item>

<item path = "women/6.jpg" type = "bitmapfile">
<title>Trish McEvoy No.6</title>
<description1>Trish McEvoy No. 6 Mandarin & Ginger </description1>
<description2>50 ml / 1.7 fl oz Eau de Toilette</description2>
<description3>Authenticity: 100% Guaranteed</description3>
<price>35</price>
<note></note>
</item>

</items>

我的PHP代码有什么问题,如何删除最后一个并在XML文件中插入一个新项目然后在最后添加???

我应该在PHP中使用      $ file = fopen($ xmlfile,“a +”); 要么      $ file = fopen($ xmlfile,“r +”);

2 个答案:

答案 0 :(得分:0)

$newItem = '<item>test</item>';

echo str_replace('</items>', $newItem.'</items>', file_get_contents($file));

答案 1 :(得分:0)

这样你就可以删除最后10个字符......

$xml = "...";
$xml = substr($xml, 0, strlen($xml)-10);

但这不像“fabrik”所说的那样。