如何检测:
$d = new DOMDocument();
$d->loadXML('
');
$sxe = simplexml_import_dom($d);
$namespaces = $sxe->getDocNamespaces(true);
$x = new DOMXpath($d);
foreach($namespaces as $prefix => $url){
$count = $x->evaluate("count(//*[namespace-uri()='".$url."' or @*[namespace-uri()='".$url."']])");
echo $prefix.' ( '.$url.' ): used '.$count.' times'.PHP_EOL;
}
如何删除:pfff,关于我唯一知道的选项是使用xml_parse_into_struct()(因为这不是libxml2 reliant afaik),并使用XML Writer函数循环生成的数组,跳过未使用的名称空间声明.没有一个有趣的通行时间,所以我将把实施留给你.根据this question,另一种选择可能是XSL,但我怀疑它有多大用处.我的最大努力似乎取得了成功,但将“顶级”/ rootnode命名空间移动到了子节点,导致更加混乱.
编辑:这似乎工作:
给定XML(添加了一些命名空间混乱):
xmlns:someprefix="http://mynamespace/foo"
xmlns:otherprefix="http://mynamespace/bar"
foo="bar"
yetanotherprefix:bax="foz">
使用基于以前$used数组的xsl(namespaces& not()子句,所以你仍然需要afaik.
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
xmlns:yetanotherprefix="http://mynamespace/yet"
xmlns:otherprefix="http://mynamespace/bar">
结果是: