我现在正在使用函数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);
真诚地感谢你。
答案 0 :(得分: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"]');
...
}
答案 1 :(得分: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);