用php替换xml节点和属性

时间:2010-02-01 02:32:16

标签: php xml

我有一个“ stuff.xml ”文件,基本上如下所示:

      <?xml version="1.0" encoding="utf-8"?>
    <mystuff>
        <pic id="pic1" _level="1" _xpos="50" _ypos="50" _width="150" _height="150">
           image.jpg
        </pic>
    </mystuff>

我需要的是三个php文件:“ image.php ”,“ pos.php ”和“ size.php “这基本上在执行时替换” stuff.xml “文件中的值。

请帮帮我。非常感谢你的进步。

1 个答案:

答案 0 :(得分:0)

另一个版本作为一个小的PHP处理类,它也可以在一个文件中处理多个图片

<?php
class StuffHandler {
    protected $_xml;

    public function __construct($filename) {
        if (file_exists($filename)) {
            $this->_xml = simplexml_load_file($filename);
            // Could it be loaded
            if ($this->_xml === false)
                throw new Exception('Could not load xml file');
        } else {
            throw new Exception('Could not load xml file');
        }
    }

    public function change_attribute($index, $attribute, $value) {
        if (isset($this->_xml->pic[$index]))
            if (isset($this->_xml->pic[$index][$attribute]))
                $this->_xml->pic[$index][$attribute] = $value;
            else
                $this->_xml->pic[$index]->addAttribute($attribute, $value);

        return $this;
    }

    public function change_value($index, $value) {
        if (isset($this->_xml->pic[$index]))
            $this->_xml->pic[$index] = $value;
        return $this;
    }

    public function save($filename) {
        $this->_xml->asXML($filename);
        return $this;
    }
}

// Loading the file
$stuff = new StuffHandler('stuff.xml');
// Change some values for the first pic
$stuff->change_value(0, 'newimage.jpg')
      ->change_attribute(0, '_xpos', 100)
      ->change_attribute(0, '_ypos', 200)
      ->save('stuff.xml);

Correspondig stuff.xml

<?xml version="1.0" encoding="utf-8"?>
<mystuff>
    <pic id="pic1" _level="1" _xpos="50" _ypos="50" _width="150" _height="150">
       image.jpg
    </pic>
    <pic id="pic2" _level="1" _xpos="50" _ypos="50" _width="150" _height="150">
       image2.jpg
    </pic>
    <pic id="pic3" _level="1" _xpos="50" _ypos="50" _width="150" _height="150">
       image3.jpg
    </pic>
</mystuff>