SitePoint Sponsor

User Tag List

Results 1 to 15 of 15

Thread: Xml To Array

  1. #1
    SitePoint Zealot marcoBR's Avatar
    Join Date
    Jun 2002
    Location
    Brazil
    Posts
    149
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Xml To Array

    Hi!

    Could someone provide a snippet of code that would show me how to parse simple XML data, without any attributes, into an associative array?

    PHP Code:
    //xml fragment
    $xml '<people>
        <person>
            <id>1</id>
            <name>Joe Cool</name>
            <age>24</age>
            <sex>male</sex>
        </person>
        <person>
            <id>2</id>
            <name>Mary Cool</name>
            <age>32</age>
            <sex>female</sex>
        </person>
    </people>'
    ;

    //desired result
    $people = array(array('id'=>'1''name'=>'Joe
    Cool'
    'age'=>'24''sex'=>'male'),
     array(
    'id'=>'2''name'=>'Mary cool''age'=>'32''sex'=>'female'));
    //eq
    $people[0]['id'] = '1';
    $people[0]['name'] = 'Joe Cool';
    $people[0]['age'] = '24';
    $people[0]['sex'] = 'male';
    $people[1]['id'] = '2';
    $people[1]['name'] = 'Mary Cool';
    $people[1]['age'] = '32';
    $people[1]['sex'] = 'female'


    Regards,

    marcoBR
    Last edited by marcoBR; Jan 5, 2003 at 14:49.

  2. #2
    Sultan of Ping jofa's Avatar
    Join Date
    Mar 2002
    Location
    SvÝ■jˇ­
    Posts
    4,080
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Don't know why you want to put the data into an array, isn't a dom document a better "container"?
    Anyway; here's a simple example:
    Code:
    <?
    $xml = "<?xml version=\"1.0\"?>
    <people>
        <person>
            <id>1</id>
            <name>Joe Cool</name>
            <age>24</age>
            <sex>male</sex>
        </person>
        <person>
            <id>2</id>
            <name>Mary Cool</name>
            <age>32</age>
            <sex>female</sex>
        </person>
    </people>";
    $domdoc = new COM("MSXML2.DOMDocument");
    $domdoc->LoadXML($xml);
    if($domdoc->parseError->errorCode != 0)
    {
    	echo $domdoc->parseError->reason;
    	exit;
    }
    else
    {
    	$root = $domdoc->documentElement;
    	$people = $root->childNodes;
    	for($i = 0; $i < $people->length; $i++)
    	{
    		$person = $people->item($i);
    		$person_props = $person->childNodes;
    		for($j = 0; $j < $person_props->length; $j++)
    		{
    			$person_prop = $person_props->item($j);
    			$person_arr[$person_prop->nodeName] = $person_prop->text;
    		}
    		$people_arr[] = $person_arr;
    	}
    	echo "<pre>";
    	print_r($people_arr);
    	echo "</pre>";
    }
    ?>
    Of course, this will only work on Windows (with MSXML installed), but I guess working with php's DomDocument object isn't much different
    Last edited by jofa; Jan 5, 2003 at 09:03.

  3. #3
    SitePoint Zealot marcoBR's Avatar
    Join Date
    Jun 2002
    Location
    Brazil
    Posts
    149
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    jofa: Don't know why you want to put the data into an array...
    Simply because array is a php data structure, and I can use all native php array functions to treat it.

    What would be equivalent in php-dom to $people->item($i)???
    Last edited by marcoBR; Jan 5, 2003 at 14:51.

  4. #4
    SitePoint Wizard Mincer's Avatar
    Join Date
    Mar 2001
    Location
    London | UK
    Posts
    1,140
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I was just browsing around Zend and I noticed this code that may be of use to you.

    http://www.zend.com/codex.php?id=982&single=1

    Matt.

  5. #5
    SitePoint Zealot marcoBR's Avatar
    Join Date
    Jun 2002
    Location
    Brazil
    Posts
    149
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Searching in php books I found a simple solution to transform XML to ARRAY

    Code:
    <!-- articles.xml -->
    <?xml version="1.0" ?>
    <dev_articles>
    	<article id="310">
    		<title>Building a Multi-Page Article System With ASP/PHP</title>
    		<url>http://www.devarticles.com/art/1/310</url>
    		<doc_type>Tutorial</doc_type>
    		<author>
    			<name>Mitchell Harper</name>
    			<email>admin@reserva.com</email>
    		</author>
    		<summary>Interested in building your own CMS? In this article Mitchell shows us how to build...</summary>
    		<image>article_310.jpg</image>
    		<date_added>20030105011450</date_added>
    	</article>
    	<article id="309">
    		<title>Getting Intimate With PHP&#39;s Mail() Function</title>
    		<url>http://www.devarticles.com/art/1/309</url>
    		<doc_type>Tutorial</doc_type>
    		<author>
    			<name>Steve Knoblock</name>
    			<email>stevek@devarticles.com</email>
    		</author>
    		<summary>Interested in sending advanced email using PHP&#39;s mail() function... </summary> 
    		<image>article_309.jpg</image>
    		<date_added>20030102184303</date_added>
    	</article>
    </dev_articles>

    PHP Code:
    function fetch_xml($xml){

        if(
    is_file($xml)){
            
    $xml_data file_get_contents($xml);
        }
        else{
            
    $xml_data $xml;    
        }
        
    $parser xml_parser_create();
        
    xml_parse_into_struct($parser$xml_data, &$assoc_arr, &$idx_arr);
        
    xml_parser_set_option($parserXML_OPTION_CASE_FOLDING0);
        
    xml_parser_set_option($parserXML_OPTION_SKIP_WHITE1);
        
    $root_tag $assoc_arr[0]['tag'];
        
    $base_tag strtolower($assoc_arr[1]['tag']);
        
    $i 0;
        foreach(
    $assoc_arr as $key => $element){
            if(
    $element['tag'] != $root_tag){
                if(!
    preg_match('/^\s+$/'$element['value'])){
                    
    $tag strtolower($element['tag']);
                    
    $items[$i][$tag] = $element['value'];
                    if(
    $tag == $base_tag){
                        
    $i++;
                    }
                }
                elseif(isset(
    $element['attributes'])){
                    
    $items[$i]['id'] = $element['attributes']['ID'];
                }
            }
        }

        return 
    $items;
    }

    $items fetch_xml('articles.xml');

    echo 
    '<pre>';
    print_r($items);
    echo 
    '</pre>'

    PHP Code:
    //Results
    Array
    (
        [
    0] => Array
            (
                [
    id] => 310
                
    [title] => Building a Multi-Page Article System With ASP/PHP
                
    [url] => http://www.devarticles.com/art/1/310
                
    [doc_type] => Tutorial
                
    [name] => Mitchell Harper
                
    [email] => admin@reserva.com
                
    [author] => 
                [
    summary] => Interested in building your own CMSIn this article Mitchell shows us how to build...            
                [
    image] => article_310.jpg
                
    [date_added] => 20030105011450
                
    [article] => 
            )

        [
    1] => Array
            (
                [
    id] => 309
                
    [title] => Getting Intimate With PHP's Mail() Function
                [url] => http://www.devarticles.com/art/1/309
                [doc_type] => Tutorial
                [name] => Steve Knoblock
                [email] => stevek@devarticles.com
                [author] => 
                [summary] => Interested in sending advanced email using PHP'
    s mail() function...
                [
    image] => article_309.jpg
                
    [date_added] => 20030102184303
                
    [article] => 
            )


    But I still needing your help to improve this code ...

    1) I would like to set keys based in the element level on the tree, for example in articles.xml author element has the child nodes name and email, thus the array keys should be [author_name] and [author_email] instead [name] and[email]. How to improve this in a undefined deep level???

    2) How to improve parse to undefined number of attributes for undefined elements???

  6. #6
    SitePoint Addict whofarted's Avatar
    Join Date
    Aug 2001
    Location
    lost, If you find me please return me to St.Louis
    Posts
    396
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Mincer
    I was just browsing around Zend and I noticed this code that may be of use to you.

    http://www.zend.com/codex.php?id=982&single=1

    Matt. [img]images/smilies/smile.gif[/img]
    All I get is an error with that code

    Fatal error: Cannot pass parameter 1 by reference in d:\web\apache\htdocs\test\example2.php on line 144

    line 144

    $xml = new XML_Array('http://www.slashdot.org/slashdot.xml',array('backslash'),array('story' => '_array_'),true,false);


    whats that all about?
    You smell something?

  7. #7
    SitePoint Wizard gold trophysilver trophy
    Join Date
    Nov 2000
    Location
    Switzerland
    Posts
    2,479
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Just as a tip off, PHP5 brings a new (built in) extension SimpleXML which should make the problem this simple;

    PHP Code:
    <?php
    $array 
    = new Simple_XML($xml);
    ?>

  8. #8
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Wow... As Simple as that ?

  9. #9
    SitePoint Zealot marcoBR's Avatar
    Join Date
    Jun 2002
    Location
    Brazil
    Posts
    149
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I don't believe... excellent!

    HarryF, where did you find it?! ... or better, where did you find PHP5 documentation?!

  10. #10
    SitePoint Zealot
    Join Date
    Aug 2002
    Posts
    178
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

  11. #11
    SitePoint Zealot
    Join Date
    Aug 2002
    Posts
    178
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

  12. #12
    Mlle. Ledoyen silver trophy seanf's Avatar
    Join Date
    Jan 2001
    Location
    UK
    Posts
    7,168
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Off Topic:

    Sort of off-topic here. What does pecl actually stand for? I see it all the time, but have never seen any explanation of the name

    Sean
    Harry Potter

    -- You lived inside my world so softly
    -- Protected only by the kindness of your nature

  13. #13
    Talk to the /dev/null Theiggsta's Avatar
    Join Date
    Mar 2001
    Location
    Tampa, FL
    Posts
    376
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PECL - PEAR Extended Code Language
    Aaron "Theiggsta" Kalin
    Pixel Martini
    Ruby and Rails Developer

  14. #14
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Had a look at those examples and I'm already impressed Think I'll definitely be downloading PHP5 some time very soon...

  15. #15
    Mlle. Ledoyen silver trophy seanf's Avatar
    Join Date
    Jan 2001
    Location
    UK
    Posts
    7,168
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Off Topic:

    Thank you Theiggsta

    Sean
    Harry Potter

    -- You lived inside my world so softly
    -- Protected only by the kindness of your nature


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •