sql >> Databáze >  >> RDS >> Mysql

Přiřazení xml generovaného smyčkou while k proměnné

Zde je návod, jak to udělat s DOM :

function createUserDetailsXml(array $result) {

    $dom  = new DOMDocument;
    $dom->formatOutput = TRUE; // enable automatic indenting
    $dom->loadXML('<users/>'); // 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
};

Všimněte si, že funkce očekává, že předáte úplné pole výsledků, takže bych to mohl otestovat pomocí:

$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 <blink>"Frigging"</blink> Doe',
        'points'   => 0,
        'imageURL' => 'http://example.com/johndoe.jpg',
        'thumbURL' => 'http://example.com/t_johndoe.jpg'
    )
);
echo createUserDetailsXml($result);

Funkce se poté vrátí

<?xml version="1.0"?>
<users>
  <user-details>
    <user-id>1</user-id>
    <user-name>Gordon</user-name>
    <user-points>2147483647</user-points>
    <image-url>http://example.com/gordon.jpg</image-url>
    <thumb-url>http://example.com/t_gordon.jpg</thumb-url>
  </user-details>
  <user-details>
    <user-id>2</user-id>
    <user-name>John &lt;blink&gt;"Frigging"&lt;/blink&gt; Doe</user-name>
    <user-points>0</user-points>
    <image-url>http://example.com/johndoe.jpg</image-url>
    <thumb-url>http://example.com/t_johndoe.jpg</thumb-url>
  </user-details>
</users>

Všimněte si prosím, že DOM automaticky unikal speciálním znakům ve jménu Johna Doea. DOM také zajistí, že názvy prvků XML (nebo atributy, pokud je používáte) jsou syntakticky platné. Také přidal XML Prolog.




  1. $PATH se neukládá poté, co opustím terminál

  2. Doba trvání ukládání MySQL - datový typ?

  3. Řešení indexu pro uživatele tabulky je poškozené; zkuste to opravit

  4. SYSDATETIMEOFFSET() Příklady v SQL Server (T-SQL)