我一直在尝试使用SimpleXML,但它似乎不喜欢看起来像这样的 XML:
<xhtml:div>sample <xhtml:em>italic</xhtml:em> text</xhtml:div>
那么哪个库会处理看起来像这样的标签(其中有一个冒号)?
我一直在尝试使用SimpleXML,但它似乎不喜欢看起来像这样的 XML:
<xhtml:div>sample <xhtml:em>italic</xhtml:em> text</xhtml:div>
那么哪个库会处理看起来像这样的标签(其中有一个冒号)?
假设你有一些这样的 xml。
<xhtml:div>
<xhtml:em>italic</xhtml:em>
<date>2010-02-01 06:00</date>
</xhtml:div>
您可以像这样访问“他们”:$xml->children('xhtml', true)->div->em;
但是,如果你想要日期字段,这:$xml->children('xhtml', true)->div->date;
不会工作,因为你被困在 xhtml 命名空间中。
您必须再次执行 'children' 才能返回默认命名空间:
$xml->children('xhtml', true)->div->children()->date;
如果您想快速修复它,请执行此操作(当我感到懒惰时我会这样做):
// 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).
冒号表示 XML 命名空间。DOM对命名空间有很好的支持。
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.