PHP DOM XML - 创建多个命名空间属性?

Sjw*_*ies 7 php xml dom

我正在研究一些PHP,使用DOM扩展从数据库创建XML.

基本上,我需要创建一个NameSpace并为其添加3个属性:

<NameSpaceName xmlns="uri:xxx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="uri:xxx">
Run Code Online (Sandbox Code Playgroud)

我写的完整代码如下:

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;
Run Code Online (Sandbox Code Playgroud)

但是当我执行上面的操作时,我得到了这个错误:

致命错误:xml.php中带有消息'Namespace Error'的未捕获异常'DOMException':21堆栈跟踪:#0 xml.php(21):DOMElement-> setAttributeNS(' http://www.w3.o ... ','xsi:schemaLocat ...','uri:xxx ...')在第21行的xml.php中抛出#1 {main}

第21行是第二个'setAttributeNS'行.

谁能看到我哪里出错?

Vol*_*erK 18

schemaLocation未在命名空间http://www.w3.org/2000/xmlns/中声明,但在http://www.w3.org/2001/XMLSchema-instance

<?php
// create a new XML document
$doc = new DomDocument('1.0', 'UTF-8');
// create root node
$root = $doc->createElementNS('http://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/2001/XMLSchema-instance', 'schemaLocation', 'http://xxx');

echo $doc->savexml();
Run Code Online (Sandbox Code Playgroud)

版画

<?xml version="1.0" encoding="UTF-8"?>
<PayerRecords xmlns="http://xxx" 
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://xxx"/>
Run Code Online (Sandbox Code Playgroud)