0

I want to create an xml file from a database, and then to echo this file to use in another page for some ajax.

this is the code I use to create the xml file :

<?php

    header("Content-Type:text/XML");

    $connexion = new PDO("mysql:host=localhost;dbname=produits;charset=utf8", 'root', 'toor'); 
    $statement = $connexion->prepare("SELECT * FROM produit"); 
    $statement->execute();

    $resultats = $statement->fetchAll(PDO::FETCH_OBJ);

    $xml_file = new DOMDocument('1.0');

    $root = $xml_file->createElement('produits');


    foreach($resultats as $produit){

        $tel = $xml_file->createElement('telephone');
        $tel->setAttribute('id', $produit->id);

        $marque = $xml_file->createElement('marque');
        $marqueText = $xml_file->createTextNode($produit->marque);
        $marque->appendChild($marqueText);
        $tel->appendChild($marque);

        $model = $xml_file->createElement('model');
        $modelText = $xml_file->createTextNode($produit->model);
        $model->appendChild($modelText);
        $tel->appendChild($model);

        $prix = $xml_file->createElement('prix');
        $prix->setAttribute("devise", "DH");
        $prixText = $xml_file->createTextNode($produit->prix);
        $prix->appendChild($prixText);
        $tel->appendChild($prix);

        $root->appendChild($tel);
    }

    $xml_file->appendChild($root);

    echo $xml_file;
?>

The problem is when I open the page to check if the xml file is create, I get this error message :

XML Parsing Error: junk after document element Location: http://localhost/Ajax/produits/details.php Line Number 2, Column 1: ^

How can I solve this problem ?

4
  • 1
    What does the outputted XML look like? Commented Mar 19, 2014 at 15:48
  • 3
    echo $xml_file->saveXML(); Commented Mar 19, 2014 at 15:49
  • @VolkerK: Good catch. I didn't even notice they weren't actually echoing the XML. Commented Mar 19, 2014 at 15:50
  • It would be helpful to future visitors if @VolkerK woudl post his comment as an answer and the OP would accept it. Commented Jul 7, 2015 at 9:33

1 Answer 1

1

$xml_file points to the DOMDocument instance. DOMDocument doesn't implement an implicit __toString() conversion, therefore echo $xml_file; results in output like

Catchable fatal error: Object of class DOMDocument could not be converted to string in ...

and the client-side xml parser complains about it not being a valid xml doc.

You want to output the xml representation of the dom which you can do e.g. via

echo $xml_file->saveXML();

see http://docs.php.net/domdocument.savexml

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.