7
votes

PHP DOM XML - Créez plusieurs attributs d'espace de noms?

Je travaille sur certains PHP pour créer XML à partir d'une base de données à l'aide de l'extension DOM.

Fondamentalement, j'ai besoin de créer un espace de noms et d'ajouter 3 attributs: P>

include_once("includes/connect.php");

$sql = ("SELECT * FROM tableName");
$query = mysql_query($sql) or die("Error: " . mysql_error());


// create a new XML document
$doc = new DomDocument('1.0', 'UTF-8');

// create root node
$root = $doc->createElementNS('uri:xxx', 'PayerRecords');
$root = $doc->appendChild($root);
$root->setAttributeNS('http://www.w3.org/2000/xmlns/' ,'xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
$root->setAttributeNS('http://www.w3.org/2000/xmlns/' ,'xsi:schemaLocation', 'uri:xxx');

// process one row at a time
while($row = mysql_fetch_assoc($query)) {

  // add node for each row
  $occ = $doc->createElement('Content');
  $occ = $root->appendChild($occ);

  // add a child node for each field
  foreach ($row as $fieldname => $fieldvalue) {

    $child = $doc->createElement($fieldname);
    $child = $occ->appendChild($child);

    $value = $doc->createTextNode($fieldvalue);
    $value = $child->appendChild($value);

  } // foreach

} // while

// get completed xml document
$xml_string = $doc->saveXML();

echo $xml_string;


0 commentaires

3 Réponses :


2
votes

Remplacer la ligne 21 avec

$root->setAttributeNS(
  'http://www.w3.org/2001/XMLSchema-instance', 
  'xsi:schemaLocation',
  'http://xxx http://xxx/xxx.xsd'
);


0 commentaires

21
votes

Schemalocation n'est pas déclaré dans l'espace de noms http://www.w3.org/2000/xmlns/ mais dans http://www.w3.org/2001/xmlschema- instance xxx

impression xxx


0 commentaires

4
votes

Je n'ai pas vraiment compris la première fois, alors je pose ma réponse plus en détail. Peut-être que quelqu'un trouve cela utile.

// create DOM document
$xml = new DomDocument('1.0', 'UTF-8');

// create root element
$el = $xml->createElementNS('http://namespaceA/url/here/', 'rootelement');

// to be able to add new namespaces we must first add namespace 'xsi'
// third parameter is important (use your main namespace with .xsd)
$root->setAttributeNS(
  'http://www.w3.org/2001/XMLSchema-instance',
  'xsi:schemaLocation',
  'http://namespaceA/url/here/ http://namespaceA/xsdfile/here.xsd');

// add new namespace
$el->setAttributeNS(
  'http://www.w3.org/2000/xmlns/',
  'xmlns:namespaceB',
  'http://namespaceB/url/here/');

// add root element to DOM
$xml->appendChild($el);


0 commentaires