获取php中每个节点的xml命名空间

时间:2011-03-01 10:06:59

标签: php xml

对于给定的xml,

<?xml version="1.0" encoding="utf-8"?>
<College xmlns:A1="zool:"xmlns:A12="dym:">
    <A1:name>Seattle</A1:name>
    <A1:MiddleName>I</A1:MiddleName>
    <A12:lastname>Roya Asbari</A12:lastname>
</College>

如何在迭代时获取每个节点的名称空间。

xml的格式每次都会有所不同,所以我正在寻找一种通用的方法。

1 个答案:

答案 0 :(得分:1)

设置XML

$xml = <<< XML
<College xmlns:A1="zool:" xmlns:A12="dym:">
    <A1:name>Seattle</A1:name>
    <A1:MiddleName>I</A1:MiddleName>
    <A12:lastname>Roya Asbari</A12:lastname>
</College>
XML;

使用DOM获取元素名称,命名空间和前缀

$dom = new DOMDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXml($xml, LIBXML_NOERROR);
foreach($dom->documentElement->childNodes as $child)
{
    printf(
        "Name: %s - NS: %s - Prefix: %s\n",
        $child->nodeName,
        $child->namespaceURI,
        $child->prefix
    );
}

输出(codepad

Name: A1:name - NS: zool: - Prefix: A1
Name: A1:MiddleName - NS: zool: - Prefix: A1
Name: A12:lastname - NS: dym: - Prefix: A12

请参阅http://php.net/manual/en/class.domnode.php