note 27015 added to function.xml-parse-into-struct
| From: | bisqwit at iki dot fi dot not dot for dot ads dot invalid | Date: | Wed, 20 Nov 2002 14:33:32 +0000 |
| Subject: | note 27015 added to function.xml-parse-into-struct | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-39756@lists.php.net to get a copy of this message | ||
I made my own xml2tree()-function.
The difference to the previously suggested ones on this manual page is that this creates a tree
where the tags are keys.
Example input:
<tree>
<leaf name="gruu"> plöö </leaf>
<animal type="cat" />
</tree>
Example output:
Array
( 'tree' => Array
( 0 => Array
( 'children' => Array
( 'leaf' => Array
( 0 => Array
( 'attrs' => Array('name' => 'gruu'),
'values' => Array(0 => ' plöö ')
) ),
'animal' => Array
( 0 => Array
( 'attrs' => Array('type' => 'cat')
) ) ) ) ) )
function xml2tree2($string)
{
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, $string, $vals, $index);
xml_parser_free($parser);
$stack = array( array() );
$stacktop = 0;
$parent = array();
foreach($vals as $val)
{
$type = $val['type'];
if($type=='open' || $type=='complete')
{
// open tag
$stack[$stacktop++] = $tagi;
$tagi = array('tag' => $val['tag']);
if(isset($val['attributes'])) $tagi['attrs'] =
$val['attributes'];
if(isset($val['value']))
$tagi['values'][] = $val['value'];
}
if($type=='complete' || $type=='close')
{
// finish tag
$tags[] = $oldtagi = $tagi;
$tagi = $stack[--$stacktop];
$oldtag = $oldtagi['tag'];
unset($oldtagi['tag']);
$tagi['children'][$oldtag][] = $oldtagi;
$parent = $tagi;
}
if($type=='cdata')
{
$tagi['values'][] = $val['value'];
}
}
return $parent['children'];
}
Ps: Note that the xml parsing for some reason chokes if the values contain <> (even inside
""). You need to escape them as < and >.
Same for & (for obvious reasons). Escape it as &.
For example " " should be written as "&nbsp;".
--
http://www.php.net/manual/en/function.xml-parse-into-struct.php
http://master.php.net/manage/user-notes.php?action=edit+27015
http://master.php.net/manage/user-notes.php?action=delete+27015
http://master.php.net/manage/user-notes.php?action=reject+27015