PHP - SimpleXML - AddChild with another SimpleXMLElement

后端 未结 3 957
野性不改
野性不改 2020-12-05 06:52

I\'m trying to build a rather complex XML document.

I have a bunch of sections of the XML document that repeats. I thought I\'d use multiple string templates as base

3条回答
  •  时光说笑
    2020-12-05 07:39

    The xml_adopt() example doesn't preserve namespace nodes.
    My edit was rejected because it changed to much? was spam?.

    Here is a version of xml_adopt() that preserves namespaces.

    function xml_adopt($root, $new, $namespace = null) {
        // first add the new node
        // NOTE: addChild does NOT escape "&" ampersands in (string)$new !!!
        //  replace them or use htmlspecialchars(). see addchild docs comments.
        $node = $root->addChild($new->getName(), (string) $new, $namespace);
        // add any attributes for the new node
        foreach($new->attributes() as $attr => $value) {
            $node->addAttribute($attr, $value);
        }
        // get all namespaces, include a blank one
        $namespaces = array_merge(array(null), $new->getNameSpaces(true));
        // add any child nodes, including optional namespace
        foreach($namespaces as $space) {
          foreach ($new->children($space) as $child) {
            xml_adopt($node, $child, $space);
          }
        }
    }
    

    (edit: example added)

    $xml = new SimpleXMLElement(
      '
      
      ');
    
    $item = new SimpleXMLElement(
      '
        Slide Title
        Some description
        http://example.com/img/image.jpg
        A1234
        
        
      ');
    
    $channel = $xml->channel;
    xml_adopt($channel, $item);
    
    // output:
    // Note that the namespace is (correctly) only preserved on the root element
    '
    
      
        
          Slide Title
          Some description
          http://example.com/img/image.jpg
          A1234
          
            
        
      
    '
    

提交回复
热议问题