Home > Backend Development > PHP Tutorial > How to Access Hyphenated Node Names in SimpleXML?

How to Access Hyphenated Node Names in SimpleXML?

Susan Sarandon
Release: 2024-12-13 13:37:10
Original
510 people have browsed it

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>
Copy after login

Trying to access the "document-meta" node using the standard syntax:

$docMeta = $officeXML->document-meta;
Copy after login

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'};
Copy after login

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'];
Copy after login

Alternate Method

If the curly brace syntax is not preferred, an alternative method is to use the following notation:

$docMeta = $officeXML->{'office:document-meta'};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template