문제

I'm trying to add entries to an XML file using DOM/PHP and I can't for the life of me get them to appear in the XML file.

The XML schema is as follows:

<alist>
    <a>
          <1>text a</1>
          <2>text a</2>
    </a>
    <a>
          <1>text b</1>
          <2>text b</2>
    </a>
</alist>

and the PHP is:

$xmlFile = "../../data/file.xml";
$dom = DOMDocument::load($xmlFile);
$v1 = "text c";
$v2 = "text c";

//create anchor
$alist = $dom->getElementsByTagName("alist");

//create elements and contents for <1> and <2>
$a1= $dom->createElement("1");
$a1->appendChild($dom->createTextNode($v1));
$a2= $dom->createElement("2");
$a2->appendChild($dom->createTextNode($v2));

//Create element <a>, add elements <1> and <2> to it.
$a= $dom->createElement("a");
$a->appendChild($v1);
$a->appendChild($v2);

//Add element <a> to <alist>
$alist->appendChild($a);

//Append entry?
$dom->save($xmlFile);
도움이 되었습니까?

해결책

getElementsByTagName() returns a list of element nodes with that tag name. You can not append nodes to the list. You can only append them to elements nodes in the list.

You need to check if the list contains nodes and read the first one.

Numeric element names like 1 or 2 are not allowed. Digits can not be the first character of an xml qualified name. Even numbering them like e1, e2, ... is a bad idea, it makes definitions difficult. If the number is needed, put it into an attribute value.

$xml = <<<XML
<alist>
    <a>
          <n1>text a</n1>
          <n2>text a</n2>
    </a>
    <a>
          <n1>text b</n1>
          <n2>text b</n2>
    </a>
</alist>
XML;

$dom = new DOMDocument();
$dom->preserveWhiteSpace = FALSE;
$dom->formatOutput = TRUE;
$dom->loadXml($xml);
$v1 = "text c";
$v2 = "text c";

// fetch the list
$list = $dom->getElementsByTagName("alist");
if ($list->length > 0) {
  $listNode = $list->item(0);

  //Create element <a>, add it to the list node.
  $a = $listNode->appendChild($dom->createElement("a"));

  $child = $a->appendChild($dom->createElement("n1"));
  $child->appendChild($dom->createTextNode($v1));

  $child = $a->appendChild($dom->createElement("n2"));
  $child->appendChild($dom->createTextNode($v2));

}

echo $dom->saveXml();

Output: https://eval.in/147562

<?xml version="1.0"?>
<alist>
  <a>
    <n1>text a</n1>
    <n2>text a</n2>
  </a>
  <a>
    <n1>text b</n1>
    <n2>text b</n2>
  </a>
  <a>
    <n1>text c</n1>
    <n2>text c</n2>
  </a>
</alist>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top