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! |
As businesses grow increasingly dependent upon Web applications to provide services to customers, employees and partners, these complex applications become more difficult to secure. Although traditional security solutions protect Internet infrastructure layers, they do not guard against HTTP and HTML attacks. Many organizations that conduct security testing still deploy applications that allow attackers to manipulate their logic and wreak havoc on their business. To mitigate this risk, development and delivery teams must address Web application security throughout the lifecycle, addressing the many layers detailed in this paper. FREE! Go There Now!
|
|
|
|
Building a software-as-a-service solution requires addressing a few key technical challenges. In this webcast, we'll focus on the role of IBM Tivoli Directory Server and WebSphere Portlet Factory in creating a Software as a Service solution. We will demonstrate how to use Tivoli Directory Server to prevent the user population of one tenant from accessing the virtual portal and portlet components of another tenant. We will also use the dynamic profile capability of WebSphere Portlet Factory to create multiple highly customized applications from one code base. FREE! Go There Now!
|
|
|
|
CakePHP is a stable production-ready, rapid-development aid for building Web sites in PHP. This "Cook up Web sites fast with CakePHP" series shows you how to build an online product catalog using CakePHP. FREE! Go There Now!
|
|
|
|
Download a free trial version of IBM DB2 9.5 for Linux, UNIX, and Windows. DB2 9 is the result of a five-year development project that transformed traditional (static) database technology into an interactive data server that merges the high performance and ease of use of DB2 with the self-describing benefits of XML. FREE! Go There Now!
|
|
|
|
Download a free trial version of IBM Rational Developer for System z, software that can help you deliver core development capabilities; the power of Java Platform, Enterprise Edition (Java EE); and rapid application development support to diverse enterprise application development teams. With comprehensive development tools to help create, deploy and maintain traditional enterprise and composite applications, Rational Developer for System z enables developers with different technical backgrounds to easily participate in important technology projects. FREE! Go There Now!
|
|
|
|
Download the IBM WebSphere Portal V6.1 beta code and learn more about the rich features and enhancements in IBM WebSphere Portal V6.1. WebSphere Portal provides a composite application or business mashup framework and the advanced tooling needed to build flexible, SOA-based solutions, and scalability to meet the needs of any size organization. FREE! Go There Now!
|
|
|
|
Join us for this web seminar to learn how you can defend your web applications from attack. Learn about the 3 most common web application attacks, including how they occur and what can be done to prevent them. We’ll also discuss manual versus automated approaches for scanning and identifying web application vulnerabilities and how IBM Rational AppScan, an automated vulnerability scanner, can help you automate more of what you are doing manually today. 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!
|
|
|
|
As organizations have grown increasingly dependent on online software, the risk of malicious attacks has also become far more serious. Fortunately, well-governed organizations can protect their Web applications by injecting vulnerability assessments and ethical hacks into their software development and delivery processes. This paper describes 12 of the most common hacker attacks and provides basic rules that you can follow to help create more hack-resistant Web applications. FREE! Go There Now!
|
|
|
|
Whether you are creating new applications or modifying existing ones, managing integration of new components with traditional z/OS elements is a critical part of building and deploying modern applications. Listen to this webcast to see how IBM can help you optimize your development process using an IDE like Rational Developer for System z that integrates with management tools, such as ClearCase to manage your application development on mainframes. FREE! Go There Now!
|
|
|
|
All FREE IBM® developerWorks Tools! |