Assigning xml generated by a while loop to a variable

前端 未结 1 1634
攒了一身酷
攒了一身酷 2020-12-10 21:49

I am creating XML using a while loop, but now I need to prepend and append the generated XML with the XML header info and wrapper tag, but I am struggling to get it to work,

1条回答
  •  时光说笑
    2020-12-10 22:11

    Here is how to do it with DOM:

    function createUserDetailsXml(array $result) {
    
        $dom  = new DOMDocument;
        $dom->formatOutput = TRUE; // enable automatic indenting
        $dom->loadXML(''); // set root node
    
        foreach($result as $row) {
    
            // create user-details node
            $user = $dom->createElement('user-details');
    
            // create and append details to user-details node
            $user->appendChild(
                $dom->createElement('user-id', $row['uid']));
            $user->appendChild(
                $dom->createElement('user-name', $row['userName']));
            $user->appendChild(
                $dom->createElement('user-points', $row['points']));
            $user->appendChild(
                $dom->createElement('image-url', $row['imageURL']));
            $user->appendChild(
                $dom->createElement('thumb-url', $row['thumbURL']));
    
            // add user-details node to XML document, e.g. users node
            $dom->documentElement->appendChild($user);
        };
        return $dom->saveXML(); // returns the formatted XML
    };
    

    Note that the function expects you to pass in the full result array, so I could test it with:

    $result = array(
        array(
            'uid'      => 1,
            'userName' => 'Gordon',
            'points'   => PHP_INT_MAX,
            'imageURL' => 'http://example.com/gordon.jpg',
            'thumbURL' => 'http://example.com/t_gordon.jpg'
        ),
        array(
            'uid'      => 2,
            'userName' => 'John "Frigging" Doe',
            'points'   => 0,
            'imageURL' => 'http://example.com/johndoe.jpg',
            'thumbURL' => 'http://example.com/t_johndoe.jpg'
        )
    );
    echo createUserDetailsXml($result);
    

    The function will then return

    
    
      
        1
        Gordon
        2147483647
        http://example.com/gordon.jpg
        http://example.com/t_gordon.jpg
      
      
        2
        John <blink>"Frigging"</blink> Doe
        0
        http://example.com/johndoe.jpg
        http://example.com/t_johndoe.jpg
      
    
    

    Please notice that DOM escaped the special chars in John Doe's name for you automatically. DOM will also make sure the XML element names (or attributes if you use them) are syntactically valid. It also added the XML Prolog.

    0 讨论(0)
提交回复
热议问题