Page 1 of 1

PHP SimpleXML and Counter

Posted: Thu May 28, 2009 12:11 pm
by fangonk
I am using simpleXML to add data to an existing XML file. The script is working properly, however I need to also include a dynamic counter that increases by one integer every time the user adds a new entry to the XML file.

For example, my XML file looks like this:

Code: Select all

 
<content>
    <category link="0">
        <title>Animals</title>
        <xml>animals.xml</xml>
    </category>
    <category link="1">
        <title>Bears</title>
        <xml>Bears.xml</xml>
    </category>
</content>
 
 
If I were to add another line to this xml file, the 'link' attribute of category tag would need to increase to 2.
 
The PHP code I am currently using to add data to the XML file looks like this:

Code: Select all

 
$str = $_SESSION['name']; 
$file = PREG_REPLACE("/[^0-9a-zA-Z]/i", '', $str);
 
if (isset($str) && !empty($str)) {
 
$simp = simplexml_load_file('galleries.xml');
$node = $simp->addChild('category');
$node->addChild('title', $str);
$node->addChild('xml', 'uploadify/xml/'.$file.'.xml');
$s = simplexml_import_dom($simp);
$s->saveXML('galleries.xml');
}
 
I can't figure out how to implement a counter that recognizes the current count of the imported XML file. Any suggestions?

Re: PHP SimpleXML and Counter

Posted: Thu May 28, 2009 12:44 pm
by requinix
Is this XML being interpreted by a program/script out of your control? Because it should be running the counter, not the XML.

You can use count($simp->category) to see how many nodes already exist...

Re: PHP SimpleXML and Counter

Posted: Thu May 28, 2009 12:51 pm
by fangonk
Yeah, unfortunately this thing is being run by a flash application that is out of my control....

Re: PHP SimpleXML and Counter

Posted: Thu May 28, 2009 1:15 pm
by fangonk
The count thing worked....

Code: Select all

 
$cfix = $count-1;
$node->addAttribute('link', $cfix);
 
Its a temporary fix though, I know I will eventually need to create a system for removing certain nodes which means I will need a script to change all of the counters on all other nodes. Ugg... I hate flash.