read and write simplexmlobject
Posted: Tue Nov 25, 2008 5:02 pm
Hello,
I want to be able to handle a simplexmlobject, almost like a normal class. Please let me know if there is something I must be aware of that might cause problems.
Is there an easier way? maybe with dom? I want to be able to add and delete children too.
I want to be able to handle a simplexmlobject, almost like a normal class. Please let me know if there is something I must be aware of that might cause problems.
Code: Select all
<?php
class TestClass
{
var $xmlData;
function loadXml($xmlstr)
{
try
{
$this->xmlData = new SimpleXMLElement($xmlstr);
}
catch (exception $ex)
{
return;
}
}
function get($path)
{
$dat = $this->xmlData->xpath($path);
return (string) $dat[0];
}
function getXml()
{
return $this->xmlData->asXML();
}
function set($path,$value)
{
$info = pathinfo($path);
$obj = $this->xmlData->xpath($info['dirname']);
$field = $info['filename'];
$obj[0]->$field = $value;
}
}
$filename = "file.xml";
$xmlFileData = file_get_contents($file);
$d = new TestClass();
$d->loadXml($xmlFileData);
echo "->" . $d->get("/Path1/Path2/Path3/field");
$d->set('/Path1/Path2/Path3/field','testing sdkjsdkjsdkj');
file_put_contents($filename,$d->getXml());