开发者

Replace xml nodes and attributes with php

I have a "stuff.xml" file which basically looks like this:

      <?xml version="1.0" encoding="utf-8"?>
    &l开发者_如何学运维t;mystuff>
        <pic id="pic1" _level="1" _xpos="50" _ypos="50" _width="150" _height="150">
           image.jpg
        </pic>
    </mystuff>

And what I need is three php files: "image.php", "pos.php", and "size.php" which basically replace values in the "stuff.xml" file when executed.

Please help me. Thank you very much in advanced.


Another version as a small php handling class which can also handle multiple pictures in one file

<?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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜