Logo         Community
The Company
Your Account
Contact Us
PHP 101 (part 11): Sinfully Simple
Change your life with SimpleXML

| The Shape Of Things To Come |

SimpleXML handles element attributes as transparently as it does elements and their content. Attribute-value pairs are represented as members of a PHP associative array, and can be accessed like regular array elements. To see how this works, take a look at this script:

// create XML string
$str = <<< XML
<?xml version="1.0"?>
    <shape type="circle" radius="2" />
    <shape type="rectangle" length="5" width="2" />
    <shape type="square" length="7" />
// load string
$xml = simplexml_load_string($str) or die ("Unable to load XML string!");

// for each shape
// calculate area
foreach ($xml->shape as $shape) {
    if ($shape['type'] == "circle") {
        $area = pi() * $shape['radius'] * $shape['radius'];
    elseif ($shape['type'] == "rectangle") {
        $area = $shape['length'] * $shape['width'];
    elseif ($shape['type'] == "square") {
        $area = $shape['length'] * $shape['length'];
    echo $area."\n";

Unlike previous examples, which used an external XML file, this one creates the XML dynamically and loads it into SimpleXML with the simplexml_load_string() method. The XML is then parsed with a foreach() loop, and the area for each shape calculated on the basis of the value of each <shape> element's type attribute. The listing above demonstrates how attribute values can be accessed as keys of the attribute array associated with each element property.

How to do Everything with PHP & MySQL
How to do Everything with PHP & MySQL, the best-selling book by Melonfire, explains how to take full advantage of PHP's built-in support for MySQL and link the results of database queries to Web pages. You'll get full details on PHP programming and MySQL database development, and then you'll learn to use these two cutting-edge technologies together. Easy-to-follow sample applications include a PHP online shopping cart, a MySQL order tracking system, and a PHP/MySQL news publishing system.

Read more, or grab your copy now!

previous page more like this  print this article  next page
In trog...
Logging With PHP
Building A Quick-And-Dirty PHP/MySQL Publishing System
Output Buffering With PHP
Date/Time Processing With PHP
Creating Web Calendars With The PEAR Calendar Class
In the hitg report...
Crime Scenes
Animal Attraction
Lord Of The Strings
In boombox...
Patience - George Michael
Think Tank - Blur
My Private Nation - Train
In colophon...
Hostage - Robert Crais
The Dead Heart - Douglas Kennedy
Right As Rain - George Pelecanos
In cut!...
American Chai
The Core
Find out how you can use this article on your own Web site!

Copyright © 1998-2018 Melonfire. All rights reserved
Terms and Conditions | Feedback