PHP library for parsing XML with a colons in tag n

2020-01-23 04:27发布

I've been trying to use SimpleXML, but it doesn't seem to like XML that looks like this:

<xhtml:div>sample <xhtml:em>italic</xhtml:em> text</xhtml:div>

So what library will handle tags that look like that (have a colon in them)?

4条回答
混吃等死
2楼-- · 2020-01-23 04:46

I don't think it's a good idea to get rid of the colon or to replace it with something else as some people suggested. You can easily access elements that have a namespace prefix. You can either pass the URL that identifies the namespace as an argument to the children() method or pass the namespace prefix and "true" to the children() method. The second approach requires PHP 5.2 and up.

SimpleXMLElement::children

查看更多
再贱就再见
3楼-- · 2020-01-23 04:53

If you want to fix it quickly do this (I do when I feel lazy):

// Will replace : in tags and attributes names with _ allowing easy access
$xml = preg_replace('~(</?|\s)([a-z0-9_]+):~is', '$1$2_', $xml);

This will convert <xhtml: to <xhtml_ and </xhtml: to </xhtml_. Kind of hacky and can fail if CDATA NameSpaced XML container blocks are involved or UNICODE tag names but I'd say you are usually safe using it (hasn't failed me yet).

查看更多
够拽才男人
4楼-- · 2020-01-23 04:58

Colon denotes an XML namespace. The DOM has good support for namespaces.

查看更多
劫难
5楼-- · 2020-01-23 05:11

Say you have some xml like this.

<xhtml:div>
  <xhtml:em>italic</xhtml:em>
  <date>2010-02-01 06:00</date>
</xhtml:div>

You can access 'em' like this: $xml->children('xhtml', true)->div->em;

however, if you want the date field, this: $xml->children('xhtml', true)->div->date; wont work, because you are stuck in the xhtml namespace.

you must execute 'children' again to get back to the default namespace:

$xml->children('xhtml', true)->div->children()->date;
查看更多
登录 后发表回答