note 103816 modified in book.simplexml by danbrown

From: Date: Thu, 05 May 2011 15:14:39 +0000
Subject: note 103816 modified in book.simplexml by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-179464@lists.php.net to get a copy of this message
The BIGGEST differece between an XML and a PHP array is that in an XML file, the name of elements can be the same even if they are siblings, eg. "<pa><ch /><ch /><ch /></pa>", while in an PHP array, the key of which must be different. I think the array structure developed by svdmeer can fit for XML, and fits well. here is an example array converted from an xml file: array( "@tag"=>"name", "@attr"=>array( "id"=>"1","class"=>"2") "@text"=>"some text", ) or if it has childrens, that can be: array( "@tag"=>"name", "@attr"=>array( "id"=>"1","class"=>"2") "@items"=>array( 0=>array( "@tag"=>"name","@text"=>"some text" ) ) Also, I wrote a function that can change that array back to XML. <?php function array2XML($arr,$root) { $xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><{$root}></{$root}>"); $f = create_function('$f,$c,$a',' foreach($a as $v) { if(isset($v["@text"])) { $ch = $c->addChild($v["@tag"],$v["@text"]); } else { $ch = $c->addChild($v["@tag"]); if(isset($v["@items"])) { $f($f,$ch,$v["@items"]); } } if(isset($v["@attr"])) { foreach($v["@attr"] as $attr => $val) { $ch->addAttribute($attr,$val); } } }'); $f($f,$xml,$arr); return $xml->asXML(); } ?> --was-- The BIGGEST differece between an XML and a PHP array is that in an XML file, the name of elements can be the same even if they are siblings, eg. "<pa><ch /><ch /><ch /></pa>", while in an PHP array, the key of which must be different. I think the array structure developed by svdmeer can fit for XML, and fits well. here is an example array converted from an xml file: array( "@tag"=>"name", "@attr"=>array( "id"=>"1","class"=>"2") "@text"=>"some text", ) or if it has childrens, that can be: array( "@tag"=>"name", "@attr"=>array( "id"=>"1","class"=>"2") "@items"=>array( 0=>array( "@tag"=>"name","@text"=>"some text" ) ) Also, I wrote a function that can change that array back to XML. function array2XML($arr,$root) { $xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><{$root}></{$root}>"); $f = create_function('$f,$c,$a',' foreach($a as $v) { if(isset($v["@text"])) { $ch = $c->addChild($v["@tag"],$v["@text"]); } else { $ch = $c->addChild($v["@tag"]); if(isset($v["@items"])) { $f($f,$ch,$v["@items"]); } } if(isset($v["@attr"])) { foreach($v["@attr"] as $attr => $val) { $ch->addAttribute($attr,$val); } } }'); $f($f,$xml,$arr); return $xml->asXML(); } http://php.net/manual/en/book.simplexml.php

« previous php.notes (#179464) next »