Vediamo se un po di codice vi stuzzica:
Codice PHP:
<?php
class XmlLoader {
public $doc = null;
public function __construct() {
$this->doc = new DOMDocument();
}
public function loadXmlFile($fileName) {
if(!is_file($fileName)){
throw new Exception('Invalid file name ['.$fileName.']');
}
if(!$this->doc->load($fileName)) {
throw new Exception('Error loading file ['.$fileName.']');
}
return new XmlParser($this->doc);
}
}
class XmlParser
{
public $doc = null;
private $_item = '';
public function __construct($doc) {
$this->doc = $doc;
$this->_item = 'item';
}
public function addElement($xmlBody) {
$item = $this->doc->createElement($this->_item);
foreach($xmlBody as $key => $value) {
$nodespace = $this->doc->createElement($key);
$nodetext = $this->doc->createTextNode($value);
$nodespace->appendChild($nodetext);
$item->appendChild($nodespace);
}
$this->doc->documentElement->appendChild($item);
}
public function getUpdatedValue($itemNum)
{
$values=array();
$item = $this->doc->getElementsByTagName("item");
if(is_null($selected=$item->item((int)$itemNum))) {
throw new Exception('Error removing item ['.$itemNum.']');
}
foreach ($selected->childNodes as $elements) {
if ($elements->nodeType == 1 ) {
if($elements->firstChild->nodeType == 3) {
$values[] = $elements->firstChild->data;
}
}
}
return $values;
}
public function removeChild($itemNum)
{
$item = $this->doc->getElementsByTagName("item");
if(is_null($item->item((int)$itemNum))) {
throw new Exception('Error removing item ['.$itemNum.']');
}
$this->doc->documentElement->removeChild($item->item((int)$itemNum));
}
public function replaceChild($xmlBody,$itemNum)
{
$item = $this->doc->createElement($this->_item);
foreach($xmlBody as $key => $value) {
$nodespace = $this->doc->createElement($key);
$nodetext = $this->doc->createTextNode($value);
$nodespace->appendChild($nodetext);
$item->appendChild($nodespace);
}
$root = $this->doc->documentElement;
$selected = $root->getElementsByTagName("item");
if(is_null($selected->item((int)$itemNum))) {
throw new Exception('Error replacing item ['.$itemNum.']');
}
$oldnode = $selected->item((int)$itemNum);
$newnode = $this->doc->importNode($item, true);
$oldnode->parentNode->replaceChild($newnode, $oldnode);
}
public function save($fileName) {
if(!$this->doc->save($fileName)){
throw new Exception('Error saving file ['.$fileName.']');
}
}
public function getItemElements()
{
$item=array();
foreach ($this->doc->documentElement->childNodes as $elements) {
if ($elements->nodeType == 1 ) {
$item[] = $elements;
}
}
return $item;
}
public function getNodesValue($item)
{
$values=array();
foreach ($item->childNodes as $elements) {
if ($elements->nodeType == 1 ) {
if($elements->firstChild->nodeType == 3) {
$values[] = $elements->firstChild->data;
}
}
}
return $values;
}
}//
?>
E un esempio di xml file:
Codice PHP:
<items>
<item>
<time>
</time>
<title>
</title>
<author>
</author>
<content>
</content>
</item>;
</items>