PHP: generare un file XML con i risultati di una query al database

PHP: generare un file XML con i risultati di una query al database

In PHP è semplice generare un documento XML a partire dai risultati di una query al database.

La soluzione è la seguente:


require_once('db-functions.php');
header('Content-Type: text/xml; charset=UTF-8');

$products = get_results('SELECT id, title, price FROM products WHERE price > 0.00 ORDER BY price LIMIT 6');
$xml = new DOMDocument('1.0', 'UTF-8');
$xml_products = $xml->createElement('Products');

foreach($products as $product) {
    $xml_product = $xml->createElement('Product');
    $id = $xml->createElement('ID', $product['id']);
    $title = $xml->createElement('Title', ucwords($product['title']));
    $price = $xml->createElement('Price', $product['price']);

    $xml_product->appendChild($id);
    $xml_product->appendChild($title);
    $xml_product->appendChild($price);

    $xml_products->appendChild($xml_product);
}

$xml->appendChild($xml_products);
echo $xml->saveXML();

Torna su