Home >Backend Development >PHP Tutorial >How to Parse XML Tags with Colons in PHP?
SimpleXML might not be the most suitable choice for parsing XML with tag names containing colons. Let's explore alternative PHP libraries that handle such scenarios.
DOMDocument is an object-oriented XML parser that provides a hierarchical representation of the XML document. It allows you to navigate and manipulate the XML tree. Here's an example:
$dom = new DOMDocument(); $dom->loadXML('<xhtml:div><xhtml:em>italic</xhtml:em><date>2010-02-01 06:00</date></xhtml:div>'); $em = $dom->getElementsByTagNameNS('http://www.w3.org/1999/xhtml', 'em')->item(0); $date = $dom->getElementsByTagName('date')->item(0); echo $em->textContent; // Output: italic echo $date->textContent; // Output: 2010-02-01 06:00
XMLReader is an event-based XML parser that provides a stream of events as it parses the XML document. You can access elements based on their namespace and local name. For example:
$reader = new XMLReader(); $reader->open('<xhtml:div><xhtml:em>italic</xhtml:em><date>2010-02-01 06:00</date></xhtml:div>'); while ($reader->read()) { if ($reader->nodeType == XMLReader::ELEMENT) { if ($reader->namespaceURI == 'http://www.w3.org/1999/xhtml') { $em = $reader->readString(); $date = $reader->readString(); } } } echo $em; // Output: italic echo $date; // Output: 2010-02-01 06:00
The above is the detailed content of How to Parse XML Tags with Colons in PHP?. For more information, please follow other related articles on the PHP Chinese website!