tags:

views:

223

answers:

2

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

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

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.

A: 

Say image.php contains a variable named $image, pos.php contained $x_pos and $y_pos, and size.php contained $width and $height, the code would look something like this:

<?php
include 'image.php';
include 'pos.php';
include 'size.php';

$xml_resource = new SimpleXMLElement('stuff.xml', 0, true);
$xml_resource->pic = $image;
$xml_resource->pic['_xpos'] = $x_pos;
$xml_resource->pic['_ypos'] = $y_pos;
$xml_resource->pic['_width'] = $width;
$xml_resource->pic['_height'] = $height;

$xml_resource->asXML('stuff.xml');
Tim Cooper
A: 

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>
tDo