read and write simplexmlobject

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
yacahuma
Forum Regular
Posts: 870
Joined: Sun Jul 01, 2007 7:11 am

read and write simplexmlobject

Post by yacahuma »

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.

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());
 
 
Is there an easier way? maybe with dom? I want to be able to add and delete children too.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: read and write simplexmlobject

Post by requinix »

Code: Select all

// echo "->" . $d->get("/Path1/Path2/Path3/field");
echo (string)$d->xmlData->Path1->Path2->Path3->field;
// maybe you mean ...->Path3["field"]?
 
// $d->set('/Path1/Path2/Path3/field','testing sdkjsdkjsdkj');
$d->xmlData->Path1->Path2->Path3->addAttribute("field", 'testing sdkjsdkjsdkj');
 
// file_put_contents($filename,$d->getXml());
$d->xmlData->asXML($filename);
Notice how I don't use any of $d's methods.

If you want to add functionality to the SimpleXML class then create a class that extends SimpleXML.
User avatar
yacahuma
Forum Regular
Posts: 870
Joined: Sun Jul 01, 2007 7:11 am

Re: read and write simplexmlobject

Post by yacahuma »

thanks
a related subject.
why this works

Code: Select all

 
$node = $obj->xpath('/Schedule/Part1/HomeMortgageInterest/PrincipalResidence');
$node[0]->NameOfEntity[4] = 'pepe';
 
but this does not? What am I missing here??

Code: Select all

 
$node = $obj->xpath('/Schedule/Part1/HomeMortgageInterest/PrincipalResidence/NameOfEntiry[4]');
$node[0] = 'jaja'; //WHAT IS MISSING
 
basically I want to change the value of the 4th element using xpath

thank you
Post Reply