我正在开发用于将错误记录到 xml 文件的简单类。
我期望的是带有 3 个子元素错误和子元素消息的根元素日志。但是输出是 Message 1Message 2Message 3 Message 1Message 2Message 3 Message 1Message 2Message 3 Everything is here 3 次。你知道为什么以及如何重写代码吗?
我得到了带有以下代码的 test.php:
<?php
require_once '../meenee/system/Logger.class.php';
$logger = new Logger;
$logger->logErrMessage("Message 1");
$logger->logErrMessage("Message 2");
$logger->logErrMessage("Message 3");
$logger->showErrLog();
日志.xml
<?xml version="1.0" encoding="UTF-8"?>
<log>
</log>
记录器类.php
class Logger{
public $errFile;
public $errXMLLog;
public function __construct(){
$this->errFile = dirname(__FILE__)."/../../error/log.xml";
if(!file_exists($this->errFile)){
throw new WarningException("File does not exists. ".$this->errFile);
}
if(!($this->errXMLLog = simplexml_load_file($this->errFile))){
throw new WarningException("Can't simple xml load file. ".$this->errFile);
}
}
public function logErrMessage($message){
$count = $this->errXMLLog->count();
$this->errXMLLog->addChild('error');
$this->errXMLLog->error[$count]->addChild('message', $message);
$this->errXMLLog->asXml($this->errFile);
}
public function showErrLog(){
foreach ($this->errXMLLog->children() as $child){
echo file_get_contents($this->errFile);
}
}
}