PHPBuilder - DOM XML: An Alternative to Expat Page 5



RSS Twitter
Articles Php Functions

DOM XML: An Alternative to Expat - Page 5

by: Matt Dunford
|
December 27, 2000

A Longer Example

Here is a longer example of how to extract info from an xml doc. For example, we have a file called employees.xml containing employee entries.
<?xml version="1.0"?>

<employees company="zoomedia.com">
	<employee>
		<name>Matt</name>
		<position type="contract">Web Guy</position>
	</employee>

	<employee>
		<name>George</name>
		<position type="full time">Mad Hacker</position>
	</employee>

	<employee>
		<name>Wookie</name>
		<position type="part time">Hairy SysAdmin</position>
	</employee>
</employees>
Here's how you would extract this info in your php script.

<?php

# iterate through an array of nodes
# looking for a text node
# return its content
function get_content($parent)
{
    
$nodes $parent->children();
    while(
$node array_shift($nodes))
        if (
$node->type == XML_TEXT_NODE)
            return 
$node->content;
    return 
"";
}

# get the content of a particular node
function find_content($parent,$name)
{
    
$nodes $parent->children();
    while(
$node array_shift($nodes))
        if (
$node->name == $name)
            return 
get_content($node);
    return 
"";
}

# get an attribute from a particular node
function find_attr($parent,$name,$attr)
{
    
$nodes $parent->children();
    while(
$node array_shift($nodes))
        if (
$node->name == $name)
            return 
$node->getattr($attr);
    return 
"";
}

# load xml doc
$doc xmldocfile("employees.xml") or die("What employees?");

# get root Node (employees)
$root $doc->root();

# get an array of employees' children
# that is each employee node
$employees $root->children();

# shift through the array 
# and print out some employee data
while($employee array_shift($employees))
{
    if (
$employee->type == XML_TEXT_NODE)
        continue;

    
$name find_content($employee,"name");
    
$pos find_content($employee,"position");
    
$type find_attr($employee,"position","type");

    echo 
"$name the $pos, $type employee<br>";
}

?>
You should see the following in your browser.
Matt the Web Guy, contract employee
George the Mad Hacker, full time employee
Wookie the Hairy SysAdmin, part time employee

« Previous Page
1
|
2
|
3
|
4
|
5
|
6
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Matt Dunford

Comment:



Comment:

(Maximum characters: 1200). You have characters left.