This function converts an xml file to an associative array. It supports multiple attributes of the same name on the same level through use of an array. It could be very useful in situations where small xml files are being used for config info.
By : simgar
<?php
// {{{ toString()
/**
* This method converts a file to a string. It returns an Error object if it is unable to open the file.
*
* @param fileName String. The name of the file to convert.
*
* @return String
* @author simgar
*/
function & toString( $fileName )
{
if ($content_array = file($fileName))
{
return implode("", $content_array);
}
else
{
// Error
return false;
}
}
// }}}
// {{{ xmlFileToArray()
/**
* This static method converts an xml file to an associative array
* duplicating the xml file structure.
*
* @param $fileName. String. The name of the xml file to convert.
* This method returns an Error object if this file does not
* exist or is invalid.
* @param $includeTopTag. booleal. Whether or not the topmost xml tag
* should be included in the array. The default value for this is false.
* @param $lowerCaseTags. boolean. Whether or not tags should be
* set to lower case. Default value for this parameter is true.
* @access public static
* @return Associative Array
* @author simgar
*/
function & xmlFileToArray($fileName, $includeTopTag = false, $lowerCaseTags = true)
{
// Definition file not found
if (!file_exists($fileName))
{
return Error::logError("File::xmlFileToArray: Failed - File '" . $fileName .
"' does not exist", __FILE__, __LINE__, SRA_ERROR_PROBLEM);
}
$p = xml_parser_create();
xml_parse_into_struct($p,File::toString($fileName),$vals,$index);
xml_parser_free($p);
$xml = array();
$levels = array();
$multipleData = array();
$prevTag = "";
$currTag = "";
$topTag = false;
foreach ($vals as $val)
{
// Open tag
if ($val["type"] == "open")
{
if (!File::_xmlFileToArrayOpen($topTag, $includeTopTag, $val, $lowerCaseTags,
$levels, $prevTag, $multipleData, $xml))
{
continue;
}
}
// Close tag
else if ($val["type"] == "close")
{
if (!File::_xmlFileToArrayClose($topTag, $includeTopTag, $val, $lowerCaseTags,
$levels, $prevTag, $multipleData, $xml))
{
continue;
}
}
// Data tag
else if ($val["type"] == "complete" && isset($val["value"]))
{
$loc =& $xml;
foreach ($levels as $level)
{
$temp =& $loc[str_replace(":arr#", "", $level)];
$loc =& $temp;
}
$tag = $val["tag"];
if ($lowerCaseTags)
{
$tag = strtolower($val["tag"]);
}
$loc[$tag] = str_replace("\\n", "\n", $val["value"]);
}
// Tag without data
else if ($val["type"] == "complete")
{
File::_xmlFileToArrayOpen($topTag, $includeTopTag, $val, $lowerCaseTags,
$levels, $prevTag, $multipleData, $xml);
File::_xmlFileToArrayClose($topTag, $includeTopTag, $val, $lowerCaseTags,
$levels, $prevTag, $multipleData, $xml);
}
}
return $xml;
}
// }}}
// {{{ _xmlFileToArrayOpen()
/**
* Private support function for File::xmlFileToArray. Handles an xml OPEN tag.
*
* @param $topTag. String. xmlFileToArray topTag variable
* @param $includeTopTag. boolean. xmlFileToArray includeTopTag variable
* @param $val. String[]. xmlFileToArray val variable
* @param $currTag. String. xmlFileToArray currTag variable
* @param $lowerCaseTags. boolean. xmlFileToArray lowerCaseTags variable
* @param $levels. String[]. xmlFileToArray levels variable
* @param $prevTag. String. xmlFileToArray prevTag variable
* @param $multipleData. boolean. xmlFileToArray multipleData variable
* @param $xml. String[]. xmlFileToArray xml variable
* @access private static
* @return boolean
* @author simgar
*/
function _xmlFileToArrayOpen(& $topTag, & $includeTopTag, & $val, & $lowerCaseTags,
& $levels, & $prevTag, & $multipleData, & $xml)
{
// don't include top tag
if (!$topTag && !$includeTopTag)
{
$topTag = $val["tag"];
return false;
}
$currTag = $val["tag"];
if ($lowerCaseTags)
{
$currTag = strtolower($val["tag"]);
}
$levels[] = $currTag;
// Multiple items w/ same name. Convert to array.
if ($prevTag === $currTag)
{
if (!array_key_exists($currTag, $multipleData) ||
!$multipleData[$currTag]["multiple"])
{
$loc =& $xml;
foreach ($levels as $level)
{
$temp =& $loc[$level];
$loc =& $temp;
}
$loc = array($loc);
$multipleData[$currTag]["multiple"] = true;
$multipleData[$currTag]["multiple_count"] = 0;
}
$multipleData[$currTag]["popped"] = false;
$levels[] = ":arr#" . ++$multipleData[$currTag]["multiple_count"];
}
else
{
$multipleData[$currTag]["multiple"] = false;
}
// Add attributes array
if (array_key_exists("attributes", $val))
{
$loc =& $xml;
foreach ($levels as $level)
{
$temp =& $loc[str_replace(":arr#", "", $level)];
$loc =& $temp;
}
$keys = array_keys($val["attributes"]);
foreach ($keys as $key)
{
$tag = $key;
if ($lowerCaseTags)
{
$tag = strtolower($tag);
}
$loc["attributes"][$tag] = & $val["attributes"][$key];
}
}
return true;
}
// }}}
// {{{ _xmlFileToArrayClose()
/**
* Private support function for File::xmlFileToArray. Handles an xml OPEN tag.
*
* @param $topTag. String. xmlFileToArray topTag variable
* @param $includeTopTag. boolean. xmlFileToArray includeTopTag variable
* @param $val. String[]. xmlFileToArray val variable
* @param $currTag. String. xmlFileToArray currTag variable
* @param $lowerCaseTags. boolean. xmlFileToArray lowerCaseTags variable
* @param $levels. String[]. xmlFileToArray levels variable
* @param $prevTag. String. xmlFileToArray prevTag variable
* @param $multipleData. boolean. xmlFileToArray multipleData variable
* @param $xml. String[]. xmlFileToArray xml variable
* @access private static
* @return boolean
* @author simgar
*/
function _xmlFileToArrayClose(& $topTag, & $includeTopTag, & $val, & $lowerCaseTags,
& $levels, & $prevTag, & $multipleData, & $xml)
{
// don't include top tag
if ($topTag && !$includeTopTag && $val["tag"] == $topTag)
{
return false;
}
if ($multipleData[$currTag]["multiple"])
{
$tkeys = array_reverse(array_keys($multipleData));
foreach ($tkeys as $tkey)
{
if ($multipleData[$tkey]["multiple"] && !$multipleData[$tkey]["popped"])
{
array_pop($levels);
$multipleData[$tkey]["popped"] = true;
break;
}
else if (!$multipleData[$tkey]["multiple"])
{
break;
}
}
}
$prevTag = array_pop($levels);
if (strpos($prevTag, "arr#"))
{
$prevTag = array_pop($levels);
}
return true;
}
// }}}
?>
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
More Database Code Articles
More By Codewalkers
developerWorks - FREE Tools! |
Effective governance for lean development isn’t about command and control. Instead, the focus is on enabling the right behaviors and practices through collaborative and supportive techniques. Hear from Scott Ambler on how it is far more effective to motivate people to do the right thing than it is to force them to do so. Learn how to form a lightweight, collaboration-based framework that reflects the realities of modern IT organizations. FREE! Go There Now!
|
|
|
|
Join us for this on demand webcast to learn about developing complex systems more quickly and efficiently. We'll cover market drivers for developing, governing and reusing systems software assets and how you can develop system software assets with Rational Asset Manager. FREE! Go There Now!
|
|
|
|
Download the Rational Application Developer (RAD) v7.5 open beta code and start developing applications for the JEE5 standard which features EJB3.0, JPA, JSF 1.2, JSP 2.1 and Servlet 2.5 standards. When you use this beta you will see how you can increase developer productivity for already existing applications with improved support for refactoring, as well as adding new features to existing applications. In addition, the beta provides tooling for JD Edwards, Oracle, SAP, Siebel and PeopleSoft to improve the developer productivity with these enterprise systems. FREE! Go There Now!
|
|
|
|
Visit IBM developerWorks to download IBM DB2 Express-C 9.5, a no-charge version of DB2 Express 9 database server. DB2 Express-C offers the same core data server base features as other DB2 Express editions and provides a solid base to build and deploy applications developed using C/C++, Java, .NET, PHP, and other programming languages. FREE! Go There Now!
|
|
|
|
Visit IBM developerWorks to download a free trial version of IBM Rational Business Developer V7.1. Rational Business Developer offers rapid and simplified development of business applications and services through Enterprise Generation Language (EGL) tools, generating Java or mainframe solutions while shielding developers from technical complexities. FREE! Go There Now!
|
|
|
|
Manage, govern, and share services across your organization by using WebSphere Service Registry and Repository. Follow the hands-on exercises to learn how to navigate the Web interface to publish, find, reuse, and update services. FREE! Go There Now!
|
|
|
|
IBM Enterprise Modernization solutions help organizations evolve core IT systems towards modern architectures and technologies—reducing the burden of maintenance and freeing up resources to develop new business requirements and capabilities. With the IBM Enterprise Modernization Sandbox for System z you can evaluate IBM Enterprise Modernization solutions focused on five key areas: Assets, Architectures, Skills, Processes and Infrastructures, and Investment. Each solution is based upon real customer experiences and offers a proven path to get you started with your modernization projects. FREE! Go There Now!
|
|
|
|
Analysts, architects, and developers who have existing COBOL or PL/I skills and want to extend those skills to deploy new workloads on the mainframe can use the IBM Enterprise Modernization Sandbox for System z to find hands-on walkthroughs of common real world scenarios. The scenarios provide examples of how to rapidly design, create, assemble, test, and deploy high-quality Web, Web services, portal, and SOA applications for IBM CICS, IBM IMS, and IBM WebSphere Application Server. FREE! Go There Now!
|
|
|
|
Asset Reuse is a key strategy for companies looking to create innovative solutions to solve complex software development problems. Searching for, identifying, updating, using and deploying software assets can be a difficult challenge. Listen to this webcast, to learn about strategies and tools that you can leverage for a successful project, including Rational Asset Manager, Rational Software Architect and WebSphere Service Registry and Repository. FREE! Go There Now!
|
|
|
|
Learn how to do more with your reusable assets with the free Rational Asset Manager eKit. The eKit includes demos on how Rational Asset Manager tracks and audits your assets in order to utilize them for reuse. Plus you’ll find white papers and a Webcast that discuss the challenges of a Service Oriented Architecture and how Rational Asset Manager can provide quick and effective solutions. FREE! Go There Now!
|
|
|
|
All FREE IBM® developerWorks Tools! |