Reply to Re: Update only Xml node (PHP5)

Your name:

Reply:


Posted by ImOk on 07/18/06 15:23

Since this is XML you may want to consider using PHP's Dom class (not
Dom XML) to do the updating.

Assuming you have this file: book.xml

<sample>
<exo id="1" value="Test" />
<exo id="2" value="Test2" />
</sample>

This example code will search for all the tags with 'exo' and change
the one whose id=='1'. It will then write back the file.

<?php
$dom=new DOMDocument();
$dom->load('book.xml');
$dom->formatOutput = true;
echo $dom->saveXML(); // show before file
$allnodes = $dom->getElementsByTagName('exo');
foreach ($allnodes as $node) {
if ($node->nodeName=='exo' and $node->getAttribute('id')=='1') {
$val=$node->getAttribute('value') . ' updated';
$node->setAttribute ( 'value', $val );
}
}
echo $dom->saveXML(); //show after file
$dom->save('book.xml');
exit;
?>



jhullu@gmail.com wrote:
> ok, it's works...
>
> thanks for your help.
>
>
> Noodle wrote:
> > You will have to read the whole file to perform this task, but if your
> > using PHP5 this can be done in 1 step, using the get
> > file_get_contents() method to read the xml document into a string.
> >
> > The following code will make the value change, and it isn't much
> > trouble to do...
> >
> > <?php
> >
> > # Set Values
> > $my_file = 'myfile.xml';
> > $new_value = 'Test updated';
> >
> > # Get file contents
> > $xml = file_get_contents($my_file);
> >
> > # Regex
> > $xml = preg_replace('<exo id="(.*)" value="(.*)" />', "exo id=\"$1\"
> > value=\"$new_value\" /", $xml);
> >
> > # Write file out again
> > file_put_contents($my_file, $xml);
> >
> > ?>
> >
> >
> > jhullu@gmail.com wrote:
> > > Hi all
> > >
> > > can I update a xml node AND write the new value in a file witout
> > > re-write all the file ?
> > >
> > > sample :
> > >
> > > my xml file :
> > >
> > > <sample>
> > > <exo id="1" value="Test" />
> > > </sample>
> > >
> > > i want to modify the file like
> > >
> > > <sample>
> > > <exo id="1" value="Test updated" />
> > > </sample>
> > >
> > > is it possible ?

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация