PHP SimpleXML and Counter

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
fangonk
Forum Newbie
Posts: 21
Joined: Thu May 14, 2009 6:43 am

PHP SimpleXML and Counter

Post 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?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: PHP SimpleXML and Counter

Post 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...
fangonk
Forum Newbie
Posts: 21
Joined: Thu May 14, 2009 6:43 am

Re: PHP SimpleXML and Counter

Post by fangonk »

Yeah, unfortunately this thing is being run by a flash application that is out of my control....
fangonk
Forum Newbie
Posts: 21
Joined: Thu May 14, 2009 6:43 am

Re: PHP SimpleXML and Counter

Post 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.
Last edited by Benjamin on Fri May 29, 2009 10:22 am, edited 1 time in total.
Reason: Changed code type from text to php.
Post Reply