I'm now using the function fwrite(); in PHP. But i want to locate my new things after a specific rule.
This wil be the output.
<?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>
How can i get the new log in the new log and not on the end. I only can find something like file_get_contents and then str_replace. But that seems really not efficient.
My php Code:
$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\" ?>
";
$xmlData .= "<logs>
";
$xmlData .= "\t<log type=\"".$data[0]."\">
";
$xmlData .= "\t\t<author>".$data[1]."</author>
";
$xmlData .= "\t\t<action>".$data[2]."</action>
";
$xmlData .= "\t\t<result>".$data[3]."</result>
";
$xmlData .= "\t\t<note>".$data[4]."</note>
";
$xmlData .- "\t</log>
";
$xmlData .= "</logs>";
} else {
}
if(is_writeable($file)) {
fwrite($fopen, $xmlData);
return true;
}
return false;
fclose($fopen);
Sincerely thank you.
Well, you're lucky your data is in XML. PHP has got a bunch of easy to use libraries (extensions) that deal with XML data. For example SimpleXML or the more capable DOM (both extension are enabled by default).
<?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"]');
...
}
You could use the array_splice
method. This way you can insert a new element in an array at any position.
$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("
", $content);
fclose($fopen);