如何通过php dom在xml上的特定节点中添加新节点

时间:2014-11-20 06:54:37

标签: php xml dom

我想将新节点插入特定节点,但我不知道该怎么做

number.xml

<numbers>
   <number>1</number>
   <number>2</number>
   <number>3</number>
   <number>4</number>
   <number>5</number>
</numbers>

number.php

<?php
$xml = new DOMDocument();
$xml->formatOutput=true;
$xml -> load('number.xml');
$xml_subnumber = $xml->createElement("subNumber");
$xml_subnumber_text = $xml->createTextNode("3.3");
$xml_subnumber->appendChild($xml_subnumber_text);
//something here (I have no idea.)
$xml->save("number.xml") or die("Error");
?>

我希望xml文件看起来像这样......

<numbers>
   <number>1</number>
   <number>2</number>
   <number>3
     <subNumber>3.3</subNumber>
   </number>
   <number>4</number>
   <number>5</number>
</numbers>

1 个答案:

答案 0 :(得分:1)

您需要找到number元素节点并将新节点附加到该节点。这是XPath。 /numbers/number[3]将返回第三个number元素节点。它将在列表中返回它,因为表达式可能返回多个节点或没有节点。这样结果类型始终保持不变。

$xml = new DOMDocument();
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;

$xml->loadXml(
  '<numbers>
   <number>1</number>
   <number>2</number>
   <number>3</number>
   <number>4</number>
   <number>5</number>
  </numbers>'
);
$xpath = new DOMXpath($xml);

foreach ($xpath->evaluate('/numbers/number[3]') as $thirdNumber) {
  $subNumber = $thirdNumber->appendChild(
     $xml->createElement("subNumber")
  );
  $subNumber->appendChild($xml->createTextNode("3.3"));
}

echo $xml->saveXml();

输出:

<?xml version="1.0"?>
<numbers>
   <number>1</number>
   <number>2</number>
   <number>3<subNumber>3.3</subNumber></number>
   <number>4</number>
   <number>5</number>
</numbers>