Database Code
  Home arrow Database Code arrow Improved XML To Array
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  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Download TestComplete 
Forums Sitemap 
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: 4 stars4 stars4 stars4 stars4 stars / 3
    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


    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!


    NEW! Best Practices: The Integrated Project and Portfolio Management Platform.

    Hear how IBM Rational Project and Portfolio Management integrated solutions help teams put the right tools and processes in place to maximize the effectiveness and efficiency of project teams and ensure that the business vision is being executed correctly. Learn how to automate and integrate requirements prioritization, top-down project planning, communications and controls, and methodology deployment to keep your scope, costs, and schedules under control. Tackle with an end-to-end approach the management of scope and scope changes, usage of methodology to control and empower project teams, and optimization of resources to align activity costs with the overall project plan.
    FREE! Go There Now!


    NEW! Cook up Web sites fast with CakePHP, Part 4: Use CakePHP&apos;s Session and Request Handler components

    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!


    NEW! Evaluate IBM Rational Developer for System i V7.1

    Download a free trial version of IBM Rational Developer for System i V7.1, which provides a complete development environment for traditional i5/OS application development. IBM Rational Developer for System i is a new eclipse-based workstation offering for i5/OS application development that provides a comprehensive Integrated Development Environment for edit/compile/debug of traditional RPG/COBOL/C/C++ i5/OS applications.
    FREE! Go There Now!


    NEW! IBM Rational AppScan Standard Edition V7.7

    Secure your Web applications with IBM Rational AppScan Standard Edition V7.7, previously known as Watchfire AppScan. This Web application security testing tool automates vulnerability assessments and scans and tests for common Web application vulnerabilities. Visit IBM developerWorks to download a free trial of IBM Rational AppScan Standard Edition V7.7.
    FREE! Go There Now!


    NEW! Improve your build process with IBM Rational Build Forge, Part 1: Create a continuous build and integration environment

    Learn how to implement a build management system that uses and extends your existing automation technologies. This tutorial shows, step-by-step, how to install and configure IBM Rational Build Forge to manage builds for Jakarta Tomcat from source code.
    FREE! Go There Now!


    NEW! Improve your build process with IBM Rational Build Forge, Part 2: Automate builds for a real-world Tomcat project

    Learn how Rational Build Forge can extend a simple compile and package build process by adding customization and deployment capability. Go from a manual method to automating: checking for code changes; getting the latest source; compiling and packaging; customizing; copying to and restarting a deployment server; and sending e-mail notification that a new version is available.
    FREE! Go There Now!


    NEW! The role of integrated requirements management in software delivery

    This paper is about the critical role that a discipline called integrated require­ments management can play in helping to ensure that your business goals and IT investments are continuously aligned—whether you are sourcing, integrat­ing, building or maintaining software. It also looks at ways that automated IBM Rational® products can work together to help you use requirements in the very best way.
    FREE! Go There Now!


    NEW! Try the IBM SOA Sandbox for Process

    Visit IBM developerWorks to try the IBM SOA Sandbox for process. The SOA Sandbox for process focuses on providing a trial environment with the necessary tooling and components required to gain a better understanding of business processes and how to best improve existing business processes to derive value quickly.
    FREE! Go There Now!


    NEW! Webcast: Introducing the new Information Server and Solutions community: LeverageInformation

    User communities play an important role in communication and collaboration around products, solutions and other areas of special interest to members. Successful communities are able to provide the right mix of content and services to deliver a value proposition that resonates with each audience. Join Tom Inman, VP of Marketing for Information and Platform Solutions as he introduces the new LeverageINFORMATION community. During this webcast, learn about the value provided by the community and how customers and partners derive value from the community in addressing their own technical and business challenges.
    FREE! Go There Now!


    NEW! Whitepaper: Achieving consistency between business process models and operational guides

    Explore how Rational and WebSphere software enable enterprise documentation in SOA environments. Specifically, a new integration between IBM WebSphere® Business Modeler and IBM Rational® Method Composer software can help technical writers more easily keep enterprise operations manuals in sync with changes that are made to business processes, resulting in more accurate and timely documentation that benefits the entire enterprise.
    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





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
    Stay green...Green IT