Home >Backend Development >PHP Tutorial >How to Access Hyphenated Node Names in SimpleXML?
SimpleXML Reading Node with Hyphenated Name
In XML, hyphens can be used in node names to improve readability. However, these hyphenated names can pose a challenge when using SimpleXML to parse the XML document.
Problem
When attempting to access a node with a hyphenated name using SimpleXML, users may encounter an error or incorrect results. For instance, with the following XML:
<gnm:Workbook xmlns:gnm="http://www.gnumeric.org/v10.dtd" ...> <office:document-meta ...> ... </office:document-meta> </gnm:Workbook>
Trying to access the "document-meta" node using the standard syntax:
$docMeta = $officeXML->document-meta;
results in an error or an incorrect integer value.
Solution
To correctly access a node with a hyphenated name in SimpleXML, enclose the node name in curly braces:
$docMeta = $officeXML->{'document-meta'};
This syntax instructs SimpleXML to treat the hyphenated name as a string and look for the node by its specific name.
Attribute Access
Note that this curly brace syntax is only necessary for accessing element nodes. Attributes with hyphenated names can be accessed using standard array notation:
$attribute = $node['hyphenated-attribute'];
Alternate Method
If the curly brace syntax is not preferred, an alternative method is to use the following notation:
$docMeta = $officeXML->{'office:document-meta'};
This explicit namespace declaration ensures that SimpleXML searches for the node within the specified namespace.
Conclusion
By using curly braces or explicit namespace declaration, users can successfully read nodes with hyphenated names in XML documents using SimpleXML.
The above is the detailed content of How to Access Hyphenated Node Names in SimpleXML?. For more information, please follow other related articles on the PHP Chinese website!