Home >Backend Development >PHP Tutorial >How Can I Access Hyphenated XML Node Names Using SimpleXML?
Reading XML Nodes with Hyphenated Names in SimpleXML
SimpleXML, a PHP library for parsing XML documents, can encounter difficulties when reading nodes with hyphenated names. For instance, consider the XML below:
<?xml version="1.0" encoding="UTF-8"?> <gnm:Workbook xmlns:gnm="http://www.gnumeric.org/v10.dtd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.gnumeric.org/v9.xsd"> <office:document-meta xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" office:version="1.1"> <office:meta> <dc:creator>Mark Baker</dc:creator> <dc:date>2010-09-01T22:49:33Z</dc:date> <meta:creation-date>2010-09-01T22:48:39Z</meta:creation-date> <meta:editing-cycles>4</meta:editing-cycles> <meta:editing-duration>PT00H04M20S</meta:editing-duration> <meta:generator>OpenOffice.org/3.1$Win32 OpenOffice.org_project/310m11$Build-9399</meta:generator> </office:meta> </office:document-meta> </gnm:Workbook>
Attempting to read the office:document-meta node using SimpleXML's children() method results in the error "Use of undefined constant meta - assumed 'meta'". This is because SimpleXML interprets the hyphen as a subtraction operator.
Solution
To overcome this issue, use curly braces instead of the hyphen:
$officeXML->{'document-meta'}
This syntax allows you to access the document-meta node.
Accessing Hyphenated Attributes
While hyphenated element names require the curly brace syntax, hyphenated attributes can be accessed using regular array notation:
$root = new SimpleXMLElement($xml); echo $root->{'hyphenated-element'}['hyphenated-attribute']; // prints "bar"
Refer to the SimpleXML Basics documentation for additional examples.
The above is the detailed content of How Can I Access Hyphenated XML Node Names Using SimpleXML?. For more information, please follow other related articles on the PHP Chinese website!