Re: SimpleXML

From: Date: Fri, 20 Aug 2004 21:58:52 +0000
Subject: Re: SimpleXML
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-194378@lists.php.net to get a copy of this message
Daniel Schierbeck wrote:
I am having some problems with the XML features (I use the fancy new SimpleXML). It works like a dream when I'm retrieving information from an XML document, but when I want to insert new tags it screws up. I'm trying to create a function that saves error logs in an XML file, which should look like this:
    <?xml version='1.0' standalone='yes'?>
    <errors>
        <error>
            <number>2</number>
            <string>Could not bla bla</string>
            <file>filename.php</file>
            <line>56</line>
        </error>
        <error>
            <number>1</number>
            <string>Failed to bla bla</string>
            <file>filename2.php</file>
            <line>123</line>
        </error>
    </errors>
I tried to use SimpleXML myself and had some strange behavior, so I ended up switching to DOM. I was already basically familiar with DOM anyway from javascript so development went quickly. You should take a look: http://www.php.net/dom There's more than one way to do it, of course, but code to add an element to this tree could look something like this: <?php // load the existing tree $doc = new DOMDocument(); $doc->load( "errors.xml" ); // count the number of existing "error" nodes $errors_node = $doc->documentElement; $error_count = $errors_node->getElementsByTagName( "error" )->length; // create the new "error" node... $error_node = $doc->createElement( "error" ); // ...and its children $number_node = $doc->createElement( "number", $error_count + 1 ); $string_node = $doc->createElement( "string", "New error message" ); $file_node = $doc->createElement( "file", "foo.php" ); $line_node = $doc->createElement( "line", "32" ); // add the children to the error node $error_node->appendChild( $number_node ); $error_node->appendChild( $string_node ); $error_node->appendChild( $file_node ); $error_node->appendChild( $line_node ); // add the new "error" node to the tree $doc->documentElement->appendChild( $error_node ); // save back to the file $doc->save( "errors.xml" ); ?> -- Rick

« previous php.general (#194378) next »