Creating sub element in XML

后端 未结 2 758
你的背包
你的背包 2020-12-21 23:07

I am trying to accomplish the following:




Harry potter
Adven         


        
2条回答
  •  有刺的猬
    2020-12-21 23:42

    Affffding nodes to the DOM requires 3 Steps

    1. Create the node using Document methods like createElement() or createTextNode()
    2. Configure the node and append child nodes
    3. Append the node to its parent node

    Step 2 and 3 are exchangeable. You can configure a node after you appended it or before. appendChild() returns the append node.

    I indented the calls depending on the level in the result xml:

    $doc = new DOMDocument('1.0');
    $doc->formatOutput = true;
    
    $books = $doc->appendChild($doc->createElement('books'));
      $book = $books->appendChild($doc->createElement('book'));
        $name = $book->appendChild($doc->createElement('name'));
          $name->appendChild($doc->createTextNode('Harry potter'));
        $category = $book->appendChild($doc->createElement('category'));
          $category->appendChild($doc->createTextNode('Adventure | Family | Fantasy'));
        $pages = $book->appendChild($doc->createElement('pages'));
          $pages->appendChild($doc->createTextNode('850'));
    
        $author = $book->appendChild($doc->createElement('author'));
          $authorName = $author->appendChild($doc->createElement('author_name'));
            $authorName->appendChild($doc->createTextNode('John Doe'));
          $authorWiki = $author->appendChild($doc->createElement('author_wiki'));
            $authorWiki->appendChild($doc->createTextNode('http://wikipedia....'));
    
        $description = $book->appendChild($doc->createElement('description'));
          $description->appendChild($doc->createTextNode('lorem ipsum blabla'));
    
    echo $doc->saveXML();
    

提交回复
热议问题