【问题标题】:PHP native XML parser [duplicate]PHP本机XML解析器[重复]
【发布时间】:2019-05-15 14:54:45
【问题描述】:

是否有不需要任何扩展或外部依赖的原生 PHP XML 解析器?

我可以使用simplexml_load_string() 进行解析,但如果服务器php 没有加载扩展,则此代码将失败。

【问题讨论】:

    标签: php xml dependencies


    【解决方案1】:

    simplexml 默认启用,因此除非您使用的是非常旧的服务器,否则您应该很好。

    在这种情况下,你可以使用这个:

    <?php 
    function xmlObjToArr($obj) { 
        $namespace = $obj->getDocNamespaces(true); 
        $namespace[NULL] = NULL; 
    
        $children = array(); 
        $attributes = array(); 
        $name = strtolower((string)$obj->getName()); 
    
        $text = trim((string)$obj); 
        if( strlen($text) <= 0 ) { 
            $text = NULL; 
        } 
    
        // get info for all namespaces 
        if(is_object($obj)) { 
            foreach( $namespace as $ns=>$nsUrl ) { 
                // atributes 
                $objAttributes = $obj->attributes($ns, true); 
                foreach( $objAttributes as $attributeName => $attributeValue ) { 
                    $attribName = strtolower(trim((string)$attributeName)); 
                    $attribVal = trim((string)$attributeValue); 
                    if (!empty($ns)) { 
                        $attribName = $ns . ':' . $attribName; 
                    } 
                    $attributes[$attribName] = $attribVal; 
                } 
    
                // children 
                $objChildren = $obj->children($ns, true); 
                foreach( $objChildren as $childName=>$child ) { 
                    $childName = strtolower((string)$childName); 
                    if( !empty($ns) ) { 
                        $childName = $ns.':'.$childName; 
                    } 
                    $children[$childName][] = xmlObjToArr($child); 
                } 
            } 
        } 
    
        return array( 
            'name'=>$name, 
            'text'=>$text, 
            'attributes'=>$attributes, 
            'children'=>$children 
        ); 
    } 
    

    来源:http://php.net/manual/pt_BR/book.simplexml.php#108688

    【讨论】:

      【解决方案2】:

      domDocument 功能可以很好地处理 html 和 xml。没有外部依赖。

      $xml = ''; //some xml string.
      
      $dom = new domDocument;
      $dom->loadHTML($xml);
      

      【讨论】:

      • 据我所知simplexml和domdocument是同一个库的两个接口
      • 我收到一个警告,ext-dom 不在composer.json 中...所以我猜这是一个依赖项?
      • Composer 不应该与它有任何关系,除非它与您的 XML 的来源有关。
      猜你喜欢
      • 1970-01-01
      • 2010-09-16
      • 1970-01-01
      • 2011-09-05
      • 1970-01-01
      • 2011-11-26
      • 2011-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多