Remove namespace from XML using PHP

前端 未结 4 1426
你的背包
你的背包 2020-12-05 19:15

I have an XML document that looks like this:



        
4条回答
  •  悲&欢浪女
    2020-12-05 19:37

    The following PHP code automatically detects the default namespace specified in the XML file under the alias "default". No all xpath queries have to be updated to include the prefix default:

    So if you want to read XML files rather they contain an default NS definition or they don't and you want to query all Something elements, you could use the following code:

    $xml = simplexml_load_file($name);
    $namespaces = $xml->getDocNamespaces();
    if (isset($namespaces[''])) {
        $defaultNamespaceUrl = $namespaces[''];
        $xml->registerXPathNamespace('default', $defaultNamespaceUrl);
        $nsprefix = 'default:';
    } else {
        $nsprefix = '';
    }
    
    $somethings = $xml->xpath('//'.$nsprefix.'Something');
    
    echo count($somethings).' times found';
    

提交回复
热议问题