使用PHP编辑XML.只有第一次工作,为什么? [英] Edit an XML with PHP. Only first time works, why?

查看:84
本文介绍了使用PHP编辑XML.只有第一次工作,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的问题是,当我编辑带有一些PHP行的XML文件(如下)时,一切都会在第一次运行,然后删除错误的行并在错误的位置创建新的行.

So my problem is that when I'm editing an XML file (below) with some PHP lines, everything works the first time, and then it deletes false lines and creates the new ones in the wrong places.

以下是用于删除行的PHP脚本:

Here the PHP script for deleting the rows:

<?php
session_start(); 

// The file
$filePath = '/....../test/test.xml';

// Grab file into an array, by lines
$fileArr = file($filePath);

// Remove desired line
unset($fileArr[7]); // $fileArr[15] == line #16
unset($fileArr[16]); // idem
unset($fileArr[25]); // idem

//Put back with PHP5
file_put_contents($filePath, implode('', $fileArr ));

session_destroy(); 
?>

在此使用PHP脚本编写新行

Here the PHP script to write new rows

<?php
session_start(); 

// The file
$filePath = '/....../test/test.xml';

// Grab file into an array, by lines
$fileArr = file($filePath);

//Change
$etichettaasse = "\t\t\t\t<string>\t14 gen</string>\n\r";
$medianord =  "\t\t\t\t<number>\t280\t</number>\n\r";
$mediasud =  "\t\t\t\t<number>\t280\t</number>\n\r";

// Replace line
$fileArr[11] = $etichettaasse;
$fileArr[19] = $medianord;
$fileArr[27] = $mediasud;

// Implode and save
file_put_contents($filePath, implode('', $fileArr ));

session_destroy(); 
?>

以下是原始 XML:

<chart>
<axis_category color='ffffff' skip='0' size='12' alpha='80' />
<axis_value color='ffffff' skip='10' size='12' show_min='false' min="80" max="130"  />
<chart_border top_thickness='1' bottom_thickness='1' left_thickness='1' right_thickness='1' />              
<chart_data>
    <row>
        <null/>
            <string>    3 dic</string>
            <string>    10 dic</string>
            <string>    17 dic</string>
            <string>    24 dic</string>
            <string>    31 dic</string>

    </row>
    <row>
        <string>Media Nord</string>
            <number>    102.72  </number>
            <number>    101.60  </number>
            <number>    101.85  </number>
            <number>    101.84  </number>
            <number>    101.84  </number>

    </row>
    <row>
        <string>Media Sud</string>
            <number>    102.28  </number>
            <number>    101.24  </number>
            <number>    101.70  </number>
            <number>    101.88  </number>
            <number>    101.88  </number>

    </row>
</chart_data>
</chart>

在第一轮PHP脚本之后,它会根据要求进行更新:

After the first round of PHP script, it is updated as requested:

<chart>
<axis_category color='ffffff' skip='0' size='12' alpha='80' />
<axis_value color='ffffff' skip='10' size='12' show_min='false' min="80" max="130"  />
<chart_border top_thickness='1' bottom_thickness='1' left_thickness='1' right_thickness='1' />              
<chart_data>
    <row>
        <null/>
            <string>    10 dic</string>
            <string>    17 dic</string>
            <string>    24 dic</string>
            <string>    31 dic</string>
            <string>    14 gen</string>

    </row>
    <row>
        <string>Media Nord</string>
            <number>    101.60  </number>
            <number>    101.85  </number>
            <number>    101.84  </number>
            <number>    101.84  </number>
            <number>    280 </number>

    </row>
    <row>
        <string>Media Sud</string>
            <number>    101.24  </number>
            <number>    101.70  </number>
            <number>    101.88  </number>
            <number>    101.88  </number>
            <number>    280 </number>

    </row>
</chart_data>

第二轮PHP脚本之后:

After the second round of the PHP script:

<chart>
<axis_category color='ffffff' skip='0' size='12' alpha='80' />
<axis_value color='ffffff' skip='10' size='12' show_min='false' min="80" max="130"  />
<chart_border top_thickness='1' bottom_thickness='1' left_thickness='1' right_thickness='1' />              
<chart_data>
    <row>
        <null/>
            <string>    17 dic</string>
            <string>    24 dic</string>
            <string>    14 gen</string>
            <string>    14 gen</string>

    </row>
    <row>
        <string>Media Nord</string>
            <number>    101.60  </number>
            <number>    101.84  </number>
            <number>    280 </number>


            <number>    280 </number>

    <row>
        <string>Media Sud</string>
            <number>    101.24  </number>
            <number>    101.70  </number>
            <number>    280 </number>


    </row>
            <number>    280 </number>

如果我只有一个PHP文件而不是2个文件,我也会很高兴,但是我不知道该怎么做.

I'd also be happy if I could have only one PHP file instead of 2, but I have no idea how to do that.

这是修改此XML文件的最佳方法,还是还有另一种方法?

Is this the best way to modify this XML file, or is there another way?

请注意,新行将由用户写入HTML.

Notice that the new line that will be written to HTML from a user.

我有这个开始"脚本,用于删除要删除的内容.

I have this "start" script for deleting the content I want to delete.

您怎么看?

<?php
$file = '/...../test.xml';


$fp = fopen(file,"w"); // open it for WRITING ("w")

if (flock($fp, LOCK_EX)) {

    //do actions here
    $xml = file_get_contents($file);
    $sxe = simplexml_load_string($xml);

    echo '<pre>';

    // "delete the 1th string of row 1, etc."
    unset($sxe->chart_data->row[0]->string[0]);
    unset($sxe->chart_data->row[1]->number[0]);
    unset($sxe->chart_data->row[2]->number[0]);

    $sxe->chart_data->row[0]->addChild('string', 'test');
    $sxe->chart_data->row[1]->addChild('number', '999');
    $sxe->chart_data->row[2]->addChild('number', '9999');

    file_put_contents($file, $sxe->asXML());


    // unlock the file
    flock($fp, LOCK_UN);

} else {

    // flock() returned false, no lock obtained
    print "Could not lock $file!\n";
}

?>

推荐答案

问题是当您unset()一个数组成员时,您更改了行号.这很容易证明:

The problem is when you unset() an array member you change the line numbers. This is easy to demonstrate:

$origfile = array(
    "line1\n",
    "line2\n",
    "line3\n",
);

unset($file[1]); // delete line 2

$round1file = implode('', $file); // "write the file"

结果是一个两行文件,而不是一个三行文件!

The result is a two-line file, not a three-line file!

line1
line3

因此,当您再次阅读它时,您的数组将如下所示:

So when you read it in again, your array will look like this:

$round1file = array("line1\n","line3\n");

如果再次删除第2行,显然会留下array("line1\n")

If you delete line 2 again, you will obviously be left with array("line1\n")

立即的解决方案是用空白行替换该行,而不是取消设置该数组成员,即$fileArr[7] = "\n"而不是unset($fileArr[7]).

The immediate solution is to replace the line with a blank line rather than to unset the array member, i.e. $fileArr[7] = "\n" instead of unset($fileArr[7]).

但是,您正在做的事情简直太疯狂了.这是一个XML文件,因此您需要使用XML库进行解析和编写,否则我保证您最终会得到无效的XML 早晚!另外,您无法安全地覆盖可能正在使用多个进程的文件-您需要使用某种文件锁定或适当的数据库.

However, what you are doing is completely insane. This is an XML file, so you need to parse and write it with an XML library or I guarantee you you will end up with invalid XML sooner or later! Also, you cannot safely write over a file that multiple processes may be using--you need to use some sort of file locking or a proper database.

对于文件锁定,您可以使用以下一对函数:

For file locking, you can use a pair of functions like this:

function file_get_contents_locked($filename)
{
    $fp = fopen($filename, 'rb');
    if ($fp===FALSE) {
        throw new RuntimeException("Could not open file '{$filename}'");
    }
    if (flock($fp, LOCK_SH)) {
        $data = stream_get_contents($fp);
        flock($fp, LOCK_UN);
        fclose($fp);
        return $data;
    } else {
            fclose($fp);
        throw new RuntimeException("Could not acquire lock on file '{$filename}'");
    }
}


function file_put_contents_locked($filename, $data)
{
    return file_put_contents($filename, $data, LOCK_EX);
}

或者,如果您使用的* nix的重命名是原子的,则可以写入临时文件并在旧文件上重命名,而不必使用锁定. (在这种情况下,您不需要锁定,因为只要使用此方法写入文件,就永远不会对其进行半读取或半写入.)

Or if you are on a *nix of some kind where renames are atomic, you can write to a temporary file and rename over the old file instead of using locking. (You don't need locking in this case because the file will never be half-read or half-written as long as you write using this method.)

function write_atomic($fullfilename, $data) {
    $tmpname = tempnam(dirname($fullfilename), 'write_atomic-');
    if (FALSE!==file_put_contents($tmpname, $data)) {
        rename($tmpname, $fillfilename);
    }
    unlink($tmpname);
}

对于XML操作,有两个简单的选项是 SimpleXML ,它更简单,但功能较弱,并且 DOMDocument 更为复杂,但功能更强大. (您也可以使用XMLReader和XMLWriter,但是它们更难使用,也更慢-仅当您无法一次将整个XML文件放入内存时才需要它们.)

For the XML manipulation, two easy options are SimpleXML which is simpler but less powerful, and DOMDocument which is more complex but more powerful. (You can also use XMLReader and XMLWriter, but these are much harder to use and much slower--they are only needed if you can't fit your entire XML file in memory at once.)

这里是一个让您入门的示例.请查看链接的文档以获取更多详细信息:

Here is an example to get you started. Look at the linked documentation for more details:

function delete_xml_stuff($filename)
{
    $xml = file_get_contents_locked($filename);
    $sxe = simplexml_load_string($xml);
    // e.g., "delete the 2th string of row 1"
    unset($sxe->chart_data->row[0]->string[1]);
    file_put_contents_locked($filename, $sxe->asXML());

    // if you have more complex criteria, use DOMDocument:

    $d = new DOMDocument();
    $d->loadXML($xml);
    $xp = new DOMXPath($d);
    $results = $xp->query('//chart_data/row[2]/*[3]');
    if ($results->length) {
        $row2column3 = $results->item(0);
        $row2column3->parentNode->removeChild($row2column3);
    }
    file_put_contents_locked($d->saveXML());
}

这篇关于使用PHP编辑XML.只有第一次工作,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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