PHP Conference Japan 2024

SimpleXMLElement::getNamespaces

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SimpleXMLElement::getNamespaces 傳回文件中使用的命名空間

說明

public SimpleXMLElement::getNamespaces(bool $recursive = false): array

傳回文件中使用的命名空間

參數

recursive (遞迴)

如果指定,則傳回父節點和子節點中使用的所有命名空間。否則,僅傳回根節點中使用的命名空間。

傳回值

getNamespaces 方法會傳回一個 陣列,其中包含命名空間名稱及其關聯的 URI。

範例

範例 #1 取得文件中使用的命名空間

<?php

$xml
= <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
<p:person id="1">John Doe</p:person>
<p:person id="2">Susie Q. Public</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getNamespaces(true);
var_dump($namespaces);

?>

上述範例將輸出:

array(1) {
  ["p"]=>
  string(21) "http://example.org/ns"
}

另請參閱

新增註解

使用者貢獻的註解 3 則註解

harry at nospam dot thestorm dot plus dot com
12 年前
如果命名空間嵌套在 XML 中,則您必須迴圈遍歷節點。

<?php




$xml
= <<<XML
<?xml version="1.0" encoding="UTF-8"?>
  <people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
      <items>
            <title>這是一個命名空間和我的耐心的測試</title>
            <p:person id="1">John Doe</p:person>
            <p:person id="2">Susie Q. Public</p:person>
            <p:person id="1">Fish Man</p:person>
      </items>
  </people>
XML;




$sxe = new SimpleXMLElement($xml);




foreach (
$sxe as $out_ns)
{
    $ns = $out_ns->getNamespaces(true);




    $child = $out_ns->children($ns['p']);




    foreach ($child as $out)
    {
        echo $out . "<br />";
    }
}
?>
harry at nospam dot thestorm dot plus dot com
12 年前
要讀取命名空間節點,您必須使用 children 方法。

<?php

$xml
= <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
<p:person id="1">John Doe</p:person>
<p:person id="2">Susie Q. Public</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$ns = $sxe->getNamespaces(true);

$child = $sxe->children($ns['p']);

foreach (
$child->person as $out_ns)
{
echo
$out_ns;
}

?>
To Top