-1

Is there a native PHP XML parser which doesn't require any extensions or external dependencies?

I can do the parsing by using simplexml_load_string(), but in case the servers php doesn't have the extension loaded, this code will fail.

Norgul
  • 4,613
  • 13
  • 61
  • 144

2 Answers2

0

The domDocument functionality deals with html and xml great. No external dependencies.

$xml = ''; //some xml string.

$dom = new domDocument;
$dom->loadHTML($xml);
Difster
  • 3,264
  • 2
  • 22
  • 32
  • As far as I know, simplexml and domdocument are two interface for the same library – splash58 Dec 14 '18 at 10:39
  • I am getting a warning for it that `ext-dom` is not in `composer.json`...so I guess it is a dependency? – Norgul Dec 14 '18 at 10:41
  • Composer shouldn't have anything to do with it unless it has something to do with where your XML is coming from. – Difster Dec 14 '18 at 10:44
0

simplexml comes enabled by default,so unless you're using a very old server you should be good.

in that case you can use this:

<?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 
    ); 
} 

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

Magus
  • 2,905
  • 28
  • 36