Home > Backend Development > PHP Tutorial > How Can I Access Hyphenated XML Node Names Using SimpleXML?

How Can I Access Hyphenated XML Node Names Using SimpleXML?

Susan Sarandon
Release: 2024-12-05 22:02:14
Original
704 people have browsed it

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

<?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>

Copy after login

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:

1

$officeXML->{'document-meta'}

Copy after login

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:

1

2

$root = new SimpleXMLElement($xml);

echo $root->{'hyphenated-element'}['hyphenated-attribute']; // prints "bar"

Copy after login

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!

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