1

我现在正在使用函数 fwrite(); 在 PHP 中。但我想在特定规则之后找到我的新事物。

这将是输出。

<?xml version="1.0" encoding="utf-8" ?> 
<logs>
    <log type="text">the new log</log>
    <log type="text>the old log</log>
    <log type="login">some other log.</log>
</logs>

我怎样才能在新日志中而不是最后获得新日志。我只能找到类似 file_get_contents 和 str_replace 的东西。但这似乎真的没有效率。

我的PHP代码:

$file = $this->path.'logs.xml';
    // Open our file. And Create file if it doesn't exsist
    $fopen = fopen($file, "w+");

    // Looks if file is empty.
    if(filesize($file) == 0) {

        /*
         * Put your data in XML data.
         */
        $xmlData = "<?xml version=\"1.0\" encoding=\"utf-8\" ?> \r\n";
        $xmlData .= "<logs> \r\n";
            $xmlData .= "\t<log type=\"".$data[0]."\">\r\n";
                $xmlData .= "\t\t<author>".$data[1]."</author>\r\n";
                $xmlData .= "\t\t<action>".$data[2]."</action>\r\n";
                $xmlData .= "\t\t<result>".$data[3]."</result>\r\n";
                $xmlData .= "\t\t<note>".$data[4]."</note>\r\n";
            $xmlData .- "\t</log>\r\n";
        $xmlData .= "</logs>";

    } else {



    }

    if(is_writeable($file)) {

        fwrite($fopen, $xmlData);
        return true;

    }
    return false;
    fclose($fopen);

衷心感谢您。

4

2 回答 2

2

好吧,您很幸运,您的数据是 XML 格式的。PHP 有一堆易于使用的库(扩展)来处理 XML 数据。例如SimpleXML或功能更强大的DOM(默认情况下启用这两个扩展)。

<?php
    $filename = $this->path.'logs.xml';

    if (!file_exists($filename)) {
       // Here's your code from above, although it would be easier to use
       // the libraries here, as well
    } else {
       $logs = simplexml_load_file($filename);
       // See if there's a "text" log element
       $txtlog = $logs->xpath('./log[@type = "text"]');
       ...
    }
于 2013-01-23T08:40:22.473 回答
2

您可以使用该array_splice方法。这样你就可以在数组的任意位置插入一个新元素。

$file = $this->path.'logs.xml';

$content = file($file); //is array with all lines as elements.

/*
0: <?xml version="1.0" encoding="utf-8" ?> 
1: <logs>
2:    <log type="text>the old log</log>
3:    <log type="login">some other log.</log>
4: </logs>
*/

//insert the new line at position 2
array_splice( $content, 2, 0, '    <log type="text">the new log</log>' );

/*
0: <?xml version="1.0" encoding="utf-8" ?> 
1: <logs>
2:    <log type="text">the new log</log>
3:    <log type="text>the old log</log>
4:    <log type="login">some other log.</log>
5: </logs>
*/

$fopen = fopen($file, "w+");
fwrite($fopen, implode("\n", $content);
fclose($fopen);
于 2013-01-23T08:41:58.087 回答