NYCPHP Meetup

NYPHP.org

[nycphp-talk] Is this XML valid?

Matt Williams mattwilliamsnyc at gmail.com
Sat Sep 19 15:05:39 EDT 2009


On Fri, Sep 18, 2009 at 23:45, David Roth <davidalanroth at gmail.com> wrote:

I've been using simplexml to parse XML and so far the XML I've had to deal
> with has been pretty straight forward. Then I run across this XML which I
> don't know what to call it or how it should be handled properly.


There are different ways to access elements and attributes of XML documents
with SimpleXML (XPath, etc), but generally speaking, attributes can be
accessed as associative array values.

Here's an example:

<?php

$xml = <<<XML
<?xml version="1.0" ?>
<document type="db download">
  <packages total_weight="15.8" total_packages="1">
    <package length="147" width="5" height="5" weight="15.8"/>
  </packages>
</document>
XML;

$sxml = new SimpleXMLElement($xml);

// Access the first package
$package = $sxml->packages->package[0];
echo sprintf(
    "Package Dimensions: %sx%sx%s Weight: %s\n",
    $package['length'],
    $package['width'],
    $package['height'],
    $package['weight']
);

// Find all packages
foreach($sxml->packages->package as $package) {
    echo sprintf(
        "Package Dimensions: %sx%sx%s Weight: %s\n",
        $package['length'],
        $package['width'],
        $package['height'],
        $package['weight']
    );
}

On Sat, Sep 19, 2009 at 14:53, David Roth <davidalanroth at gmail.com> wrote:

So if the above is valid XML, is there a specific name for this
approach? Is there a benefit for doing it this way instead of nested
nodes? Might this be considered older method?
>
>
No, it's not an older method. There is no absolute definition of when to use
elements versus attributes. There are, however, some attempts at defining
general principles:

http://www.ibm.com/developerworks/xml/library/x-eleatt.html

Also,
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.nyphp.org/pipermail/talk/attachments/20090919/f87dd100/attachment.html>


More information about the talk mailing list