KBD

Keith Devens .com

Saturday, November 22, 2008 Flag waving
Your best? Losers always whine about their best. Winners go home and fuck the prom queen. – John Mason (The Rock)
← August 6, 2001 PDBGas is cheap! (Or... games Democrats play with the economy) →

Daily link icon Wednesday, April 14, 2004

XML Serialize

This code has been a major part of my XML-RPC library from the beginning. It takes a PHP data structure and serializes it into XML (simple).

For example, the following PHP code:

<?php
$foo 
= array(
    
'foo'=> array(
        
'bar'=>array('blah','<i>blah</i>'),
        ),
    
'foo attr'=>array('att1'=>"this isn't the best song in the world"'att2'=>'this is only a "tribute"')
);
echo 
XML_serialize($foo);
?>

Generates the following XML (reformatted slightly):

<?xml version="1.0" ?>
<foo att1="this isn't the best song in the world"
att2="this is only a &quot;tribute&quot;"
>

    <bar>blah</bar>
    <bar>&lt;i&gt;blah&lt;/i&gt;</bar>
</foo>

I've recently revised the code as part of getting rid of my CMS. I was generating my RSS feed for my weblog with a template, when, since it's data, it should really be generated by a library from a data structure. The result was simpler, shorter, and more maintainable than what I had before.

Here's the code:
Update (Jul 24, '04): Code removed. An updated version is available at http://keithdevens.com/software/phpxml

Note that the data you send to XML_serialize had better already be in UTF-8 or you'll be generating invalid XML, and it's your responsibility to not try to generate invalid XML tag names. The $data passed to XML_serialize must be an array containing one element, which is the top-level element of the XML document. If you want to do namespaces, just do it manually by adding namespace attributes to the top-level element, and prefix your tag names with the appropriate namespace name.

For example, here's essentially how I go about generating my RSS (code altered slightly):

<?php
function weblog_rss(){
    
$xml = array();
    
$xml['rss attr'] = array('version'=>'2.0');
    
$xml['rss']['channel'] = array(
        
'title'=>"Keith's Weblog"
        'link'
=>'http://keithdevens.com/weblog'
        'description'
=>'The personal weblog of Keith Devens',
        
'language'=>'en-us',
        
'image'=>array(
            
'link'=>'http://keithdevens.com/weblog',
            
'title'=>'Keith Devens .com',
            
'url'=>'http://keithdevens.com/images/kbd.gif'
        
)
    );
    
$rss_items = array();
    
$entries = &weblog_getEntries();
    require_once(
'markup_library.php');
    require_once(
'xml_library.php');
    foreach(
$entries as $e){
        
$timestamp convert_mysql_datetime($e['creation_datetime']);
        
$url 'http://keithdevens.com'.weblog_getUrl('entry'$e);
        
$rss_items[] = array(
            
'title'=>utf8_encode($e['title']),
            
'link'=>$url,
            
'guid'=>'http://www.keithdevens.com/weblog/'.$e['id'],
            
'guid attr'=>array('isPermaLink'=>'false'),
            
'description'=>utf8_encode(markup($e['text'], array("enable_abs_links"=>true))),
            
'pubDate'=>date('r',$timestamp),
            
'comments'=>$url.'#comments'
        
);
    }
    
$xml['rss']['channel']['item'] = $rss_items;
    
header("Content-type: text/xml");
    echo 
xml_serialize($xml);
}
?>

All of this code should be translatable to pretty much any other scripting language. The only issue is that PHP maintains the order of keys within an associative array while most other languages don't. So, if that's important to you, the code won't be applicable in other languages as it is in PHP. However, since this is meant for data-oriented XML anyway, the order of keyed elements probably won't matter to you.

I don't look at XML as some change-the-world semantic-web savior. It's just a relatively pain-in-the-butt-to-use file format. I may release this code as well as my parser code as an open-source library separate from my XML-RPC library, though to some degree both will be obsoleted by SimpleXML in PHP 5. Anyway, consider this code public domain.

Update (May 28): I've updated this code and released it along with its corresponding XML_unserialize function as an open source library, available at http://keithdevens.com/software/phpxml.

← August 6, 2001 PDBGas is cheap! (Or... games Democrats play with the economy) →

Comments XML gif

ideoplastos (http://www.ideoplastos.net) wrote:

Dude, you gotta get the Tribute lyrics right.

∴ ideoplastos | 14-Apr-2004 2:33pm est | http://www.ideoplastos.net | #4363

Keith (http://keithdevens.com/) wrote:

Damn. What is it, "this is not the best song in the world"?

Oh, they mixed it up...

This is not The Greatest Song in the World, no.
This is just a tribute.

Fliggu giggu, a fliggu giggu, doo dee!

I'm kind of psyched you noticed Smiley

Keith | 14-Apr-2004 2:59pm est | http://keithdevens.com/ | #4364

Dennis Pallett (http://www.nocertainty.com) wrote:

Have you got an XML _un_serializer as well?

∴ Dennis Pallett | 14-Apr-2004 3:40pm est | http://www.nocertainty.com | #4365

Keith (http://keithdevens.com/) wrote:

The "unserializer" is currently built into my XML-RPC library, so you can get it there. The main reason I haven't released this code along with the unserializer (as well as version 3 of my XML-RPC library) is because of PHP's major problems with references that make it (at least almost) impossible to do this without generating lots of warnings if you have call-time-pass-by-reference disabled.

So, for now, until I release it separately, check out the library and the XML_unserialize function.

Keith | 15-Apr-2004 12:26am est | http://keithdevens.com/ | #4368

Dennis Pallett (http://www.nocertainty.com) wrote:

Okay, I'll check out the library, thanks! :-)

∴ Dennis Pallett | 17-Apr-2004 5:11pm est | http://www.nocertainty.com | #4375

Feel free to post a comment below. Please see my comment policy.

Formatting Rules (No HTML):

  • **bold**, *italic*, _underlined_, --strikeout--
  • "text"="url" creates a link, and URLs are auto-highlighted
  • Blockquote: Like e-mail, begin paragraph with > (greater-than sign)
  • Lists: begin paragraph with *,-, or + (unordered), or # (ordered)
  • Code block: ?!code:language=perl|php|sql|javascript|etc.{\n}...{\n}?!/code

:
(will be your IP address if blank)
: (optional)
(Will not be shown on site)

: (optional)
:

November 2008
SunMonTueWedThuFriSat
 1
2345678
9101112131415
16171819202122
23242526272829
30 



RSS feed RSS feed for Keith's Weblog
Atom feed Atom feed for Keith's Weblog
Weblog archive
Recent comments
  on 4 posts

Recent comments XML

Calif. Supreme Court to take up gay marriage ban

I would argue the point is not​definitional.  While the word​marriage is su...

Justin: Nov 20, 4:37pm

Java join function

Meh, don't have null strings in​your string arrays imo, but you're​welcome ...

Keith: Nov 19, 7:51pm

Girls, please don't get breast implants

sorry but another thing i have to​make a comment on about you​men...the men...

happynow: Nov 17, 11:36pm

Books by Vincent Cheung

to all Cheung​fans:

read:

http://www.progin​osko.com/aquascum/cheung.h...

Zamir: Nov 16, 9:07am

Generated in about 0.234s.

(Used 8 db queries)

mobile phone