• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • SimpleXMLElement::getNamespaces()

    (PHP 5 >= 5.1.2, PHP 7)

    Returns namespaces used in document

    说明

    publicSimpleXMLElement::getNamespaces([bool $recursive= FALSE]): array

    Returns namespaces used in document

    参数

    $recursive

    If specified, returns all namespaces used in parent and child nodes. Otherwise, returns only namespaces used in root node.

    返回值

    ThegetNamespacesmethod returns an array of namespace names with their associated URIs.

    范例

    Example #1 Get document namespaces in use

    <?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"
    }
    

    参见

    • SimpleXMLElement::getDocNamespaces() Returns namespaces declared in document
    • SimpleXMLElement::registerXPathNamespace() Creates a prefix/ns context for the next XPath query
    If the namespace is nested in the xml, then you will have to loop over the nodes.
    <?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>This is a test of namespaces and my patience</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 />";
        }
    }
    ?>
    
    To read a namespace node you have to use the children method.
    <?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;
    }
    ?>
    
    this article has more info : http://www.sitepoint.com/parsing-xml-with-simplexml/