【问题标题】:Why SIMPLE XML addChild() adds 3 childs? [closed]为什么 SIMPLE XML addChild() 添加 3 个孩子? [关闭]
【发布时间】:2013-06-14 14:25:34
【问题描述】:

我正在开发用于将错误记录到 xml 文件的简单类。

我期望的是带有 3 个子元素错误的根元素日志和子元素消息。 但输出是 Message 1Message 2Message 3 Message 1Message 2Message 3 Message 1Message 2Message 3 一切都在这里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();

log.xml

<?xml version="1.0" encoding="UTF-8"?>
<log>

</log>

Logger.class.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);
        }
    }

}

【问题讨论】:

    标签: php xml simplexml


    【解决方案1】:

    检查showErrLogproc:

    对于每个孩子(有 3 个孩子) 做 回显文件内容(整个文件内容,其中文件包含 3 条消息。)。

    -> 你回显文件内容 3 次。

    注意可能您需要添加 EOL char 来分隔文件中的行。

    【讨论】:

    • Ou.. 之前在 foreach 中还有其他内容。非常感谢您的帮助。
    猜你喜欢
    • 2011-02-23
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 2015-01-07
    相关资源
    最近更新 更多