[loulug] Re: PHP and XML

  • From: William Anderson <whanders@xxxxxxxxxxxxxxxxxxxx>
  • To: loulug@xxxxxxxxxxxxx
  • Date: Sat, 05 Jan 2008 13:29:41 -0600

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Jared,

Sorry, not familiar with SimpleXML, just the DOM stuff they added in PHP5 so the
examples below use that instead.

Unless you're planning to iterate over all the preferences each time you use
them (e.g. read through them once to store in an array for future use), XPath is
probably the simplest way to do it. Assuming you go with the newer version you
sent and you are planning on just iterating over the XML data once, you can
always just:

<?php
$xml = DOMDocument::load('config.xml');
$prefs = $xml->documentElement->getElementsByTagName('pref');

for ( var i=0; i < $prefs.length; i++ )
{
   $name = $prefs->item($i)->getAttribute('name');
   $value = $prefs->item($i)->getAttribute('value');
   $PREFS_ARRAY[$name] = $value;
}
?>




Alternately, you can change your xml to look like:

<?xml version="1.0"?>
<prefs>
   <user>jbreland</user>
   <domain>legroom.net</domain>
</prefs>

<?php
$xml = $xml = DOMDocument::load('config.xml');
function getPref ( $pref, $xml )
{
   return $xml->getElementsByTagName($pref)[0]->nodeValue;
}
?>

This has the added "feature" that, if you write a DTD or XSD for your prefs
file, you can control what prefs are stored in that file by validating your
prefs file before using it.  If a preference name is not listed in the DTD/XSD
as a valid child node of the "prefs" node, the validator will throw an error.
I'm not sure what this file is to be used for so that's probably just more
hassle than help but it can come in handy in certain situations.


Bill




Jared Breland wrote:
> Btw, this is something I'm writing, so I can control/change the XML file.
> The one that I provided below is just an example.  But, I can also do
> something like this if it'd work better:
> 
> <?xml version='1.0'?>
> <prefs>
>   <pref name="user" value="jbreland" />
>   <pref name="domain" value="legroom.net" />
> </prefs>
> 
> Whatever works.
> 
> --
> Jared Breland
> jbreland@xxxxxxxxxxx
> http://www.legroom.net/
> 

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7-ecc0.1.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFHf9qlilyqqQUn4j8RAsP9AJwIn6H5Ciu0TlNqfzqqlyWGOWESvwCgoWv1
6xZCk/U6399ZqIaw3yR79ng=
=NRur
-----END PGP SIGNATURE-----

Other related posts: