Mombu the Php Forum sponsored links

Go Back   Mombu the Php Forum > Php > note 56530 deleted from ref.xml by bjori
User Name
Password
REGISTER NOW! Mark Forums Read

sponsored links


Reply
 
1 21st December 08:29
bjori
External User
 
Posts: 1
Default note 56530 deleted from ref.xml by bjori


Note Submitter: docvert at holloway dot co dot nz

----

I see there's a few requests for a simple XML parser that doesn't depend on external libraries... this function parses a string of XML, creating nested arrays and attributes. It supports the /> syntax, multiple root nodes, whitespace in key=value attributes, and single/double quote attribute values. It doesn't, however, support text() nodes.

<?php

function par***mlString($xmlString)
{
$exitAfterManyLoops = 0;
$xmlArray = array();
$currentNode = &$xmlArray;
$currentHierarchy = array();
$currentDepth = 0;
while($xmlString != '')
{
$exitAfterManyLoops++;
if($exitAfterManyLoops > 300)
{
print "BREAK";
break;
}
$xmlString = trim(substr($xmlString, strpos($xmlString, '<')));
$thisNodeAscends = (substr($xmlString, 1, 1) == '/');
$thisNodeDescends = (substr($xmlString, strpos($xmlString, '>') - 1, 1) != '/');
$openElement = substr($xmlString, strpos($xmlString, ' ') + 1);
$openElement = substr($openElement, 0, strpos($openElement, '>') );
if(substr($openElement, strlen($openElement) - 1, 1) == "/")
{
$openElement = substr($openElement, 0, strlen($openElement) - 1);
}

if($thisNodeAscends)
{
$currentDepth--;
$currentNode = &$currentHierarchy[$currentDepth];
}
else
{
if($thisNodeDescends)
{
$currentNode[] = array('attributes' => par***mlAttributesString($openElement), 'children' => array());
$currentHierarchy[$currentDepth] = &$currentNode;
$currentDepth++;
$lastItem = &$currentNode[count($currentNode) - 1];
$currentNode = &$lastItem['children'];
}
else //this node is at the same level
{
$currentNode[] = array('attributes' => par***mlAttributesString($openElement));
}
}
$xmlString = substr($xmlString, strpos($xmlString, '>') + 1);
}
return $xmlArray;
}

function par***mlAttributesString($xmlElementString)
{
$exitAfter100Loops = 0;
$xmlElementArray = array();
while($xmlElementString != '')
{
$exitAfter100Loops++;
if($exitAfter100Loops > 100)
{
print "BREAK";
break;
}
$equalsCharacterPos = strpos($xmlElementString, '=');
$key = trim(substr($xmlElementString, 0, $equalsCharacterPos));
$xmlElementString = substr($xmlElementString, $equalsCharacterPos + 1);
$openBracket = substr($xmlElementString, 0, 1);
$xmlElementString = substr($xmlElementString, 1);
$endBracketPos = strpos($xmlElementString, $openBracket);
$value = substr($xmlElementString, 0, $endBracketPos);
$xmlElementString = substr($xmlElementString, $endBracketPos + 1);
if($key)
{
$xmlElementArray[$key]=$value;
}
}
return $xmlElementArray;
}

?>
  Reply With Quote


  sponsored links


Reply


Thread Tools
Display Modes




Copyright 2006 SmartyDevil.com - Dies Mies Jeschet Boenedoesef Douvema Enitemaus -
666