Database Code
  Home arrow Database Code arrow Improved XML To Array
Moblin
Try It Free
Codewalker Forums 
  Tutorials  
Database Articles  
Miscellaneous  
Navigation Usability  
PEAR Articles  
Programming Basics  
Server Administration  
XML Tutorials  
  Reviews  
Database Book Reviews  
Linux Book Reviews  
Miscellaneous Reviews  
PHP Book Reviews  
PHP Software Reviews  
Server Admin Reviews  
SQL Tool Reviews  
  Code Gallery  
Content Management Code  
Contest Code  
Counters Code  
Database Code  
Date Time Code  
Discussion Board Code  
Email Code  
File Manipulation Code  
GUI Code  
Link Farm Code  
Miscellaneous Code  
Search Code  
Site Navigation Code  
User Management Code  
Forums Sitemap 
Dedicated Servers  
Download TestComplete 
JMSL Numerical Library 
IBM® developerWorks
Weekly Newsletter 
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
DATABASE CODE

Improved XML To Array
By: Codewalkers
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 1
    2002-10-30

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Get inside! Sample the range of functionality easily built with JMSL Library for Time Series Data Analysis, Heat Maps, Portfolio Optimization, Monte Carlo Simulation, Stock Price Charting and more. Download Now!

    Last updated 10/30/2002

    This is an improved version of my previous XML To Array function submitted on 09/19/02. It supports XML tag attributes and also single tag XML elements. Check back for updates to this code (see last update date above).


    Old Description:
    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 or data.

    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 Jason Read <jason@ace.us.com>
    */
    function & xmlFileToArray($fileName, $includeTopTag = false, $lowerCaseTags = true)
    {
    // Definition file not found
    if (!file_exists($fileName))
    {
    // Error
    return false;
    }
    $p = xml_parser_create();
    xml_parse_into_struct($p,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 (!_xmlFileToArrayOpen($topTag, $includeTopTag, $val, $lowerCaseTags,
    $levels, $prevTag, $multipleData, $xml))
    {
    continue;
    }
    }
    // Close tag
    else if ($val["type"] == "close")
    {
    if (!_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")
    {
    _xmlFileToArrayOpen($topTag, $includeTopTag, $val, $lowerCaseTags,
    $levels, $prevTag, $multipleData, $xml);
    _xmlFileToArrayClose($topTag, $includeTopTag, $val, $lowerCaseTags,
    $levels, $prevTag, $multipleData, $xml);
    }
    }
    return $xml;
    }
    // }}}

    // {{{ _xmlFileToArrayOpen()
    /**
    * Private support function for 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 Jason Read <jason@ace.us.com>
    */
    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 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 Jason Read <jason@ace.us.com>
    */
    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

     

    IBM® developerWorks developerWorks - FREE Tools!


    Check out the new Jazz space on developerWorks

    <a href="http://zeus.developershed.com/shonuff.php?blackbird=3853&zoneid=442&source=&dest=http%3A%2F%2Fwww.ibm.com%2Fdeveloperworks%2Fspaces%2Fjazz%3FS_TACT%3D105AGY31%26S_CMP%3DDEVSHED&ismap="><img src="http://images.devshed.com/corp/img/news/jazz01.gif" alt="developerWorks Jazz space" align="left"></a>You've heard the buzz about Jazz... want to know more about it from a developer's perspective? Check out the Jazz space on developerWorks. This space is an up-to-date resource for developers, including technical information about Jazz and products built on Jazz, like Rational Team Concert Express. The Jazz space includes content from a wide variety of sources, including links, feeds, and comments from experts.
    FREE! Go There Now!


    NEW! Driving Business Success with Rational Process Library

    Join this webcast, to learn how the Rational Process Library can help with compliance issues, drive process improvement, and assist in service-oriented architecture (SOA) or Agile development. We will take a peek into the Rational Process Library with content around software and systems engineering (including RUP), operations and systems management, program and portfolio management, and asset and SOA governance.
    FREE! Go There Now!


    NEW! A Layered approach to delivering security-rich Web applications

    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!


    NEW! Applying lean thinking to the governance of software development

    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!


    NEW! Best Practices in Integrated Requirements Management

    Poor Requirements Management capabilities in an Enterprise have been linked to excessive project failures, escalating IT costs, and failure to deliver competitive advantage into the marketplace. Join Brianna M Smith from IBM Rational and learn about how successful organizations align IT and Business stakeholders through collaborative processes and tools for effective requirements management, and how an integrated approach across the IT lifecycle can provide unparalleled visibility and traceability to ensure that project teams are delivering on the business vision by "doing the right things" and "doing things right."
    FREE! Go There Now!


    NEW! Download the free Web Application Security eKit

    Discover how IBM Rational AppScan Standard Edition can help you detext vulnerabilities in your web applications in the Web Application Security eKit. IBM Rational AppScan is a leading suite of automated web application security solutions that scan and test for common Web application vulnerabilities. The new Web Application Security eKit provides you with valuable resources, including white papers, demos, and additional information on the benefits of testing your Web applications.
    FREE! Go There Now!


    NEW! Hello World: WebSphere Service Registry and Repository

    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!


    NEW! Successful Change and Release Management for .NET

    Join this webcast to discover the key requirements for successful change and release management. Learn how to extend your .NET environment to improve productivity and collaboration, and address core problems afflicting team development. In this webcast, we’ll review typical challenges faced by customers and how to resolve them with the IBM Rational Change and Release Management solution, including Rational ClearCase, Rational ClearQuest and Rational Build Forge. Replay is available for 9 months.
    FREE! Go There Now!


    NEW! Webcast: Quickly provide customized, integrated user interfaces with Lotus Notes 8

    IBM Lotus Notes 8 provides a wide range of developers the ability to provide customized, integrated user interfaces via composite applications and via custom sidebar and toolbar plug-ins. This webcast provides you with tips and techniques to use with out-of-the-box capabilities of Lotus Notes 8, and survey how you can share useful components within your own company and within a larger community.
    FREE! Go There Now!


    NEW! Webcast: Striking the right balance between manual and automated testing

    Join this webcast to learn how IBM Rational's Functional Testing solution enables you to implement automation your way, at your pace, with your existing staff. In this webcast, you’ll learn how you can eliminate redundancy of manual test scripts, reduce errors, and increase test coverage through test automation. After this presentation you will understand how IBM Rational Functional Testing solution can streamline your manual testing and make test automation easily attainable.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    DATABASE CODE ARTICLES

    - Examples and Tools for Database Design
    - Relationships, Entities and Database Design
    - Modeling and Designing Databases
    - Data extract to Excel
    - Oracle database class 0.76
    - The opposite of mysql_fetch_assoc
    - On line Thermal Transmitance Calculation
    - pjjTextBase
    - PHP Object Generator
    - FastMySQL
    - RC4PHP
    - SQL function with integrated sprintf()
    - DB Interaction Classes v1.1
    - deeMySQLParser
    - CSV to SQL convertor


    Iron Speed




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway