更改XML节点值

时间:2011-08-24 23:35:30

标签: php xml simplexml

此脚本应更改指定COMMUNITY节点的TOP值。但这不是什么错误?

<?php

function make_update( $nodeid, $name, $top, $left, $width, $height ) {

$nodes = new SimpleXMLElement('communities.xml', null, true);

$node = $nodes->xpath("//COMMUNITY[@ID='$nodeid']"); 

$node->TOP->nodeValue = $top;

$nodes->asXML();

return $top;
}

echo make_update(trim($_REQUEST['nodeid']),trim($_REQUEST['name']),trim($_REQUEST['top']),trim($_REQUEST['left']),trim($_REQUEST

['width']),trim($_REQUEST['height']));

?>

XML看起来像这样。

<?xml version="1.0" encoding="ISO-8859-1"?>
<COMMUNITIES>
<COMMUNITY ID="c001">
  <NAME>Town Services</NAME> 
  <TOP>50</TOP> 
  <LEFT>50</LEFT> 
  <WIDTH>200</WIDTH> 
  <HEIGHT>300</HEIGHT> 
  <URLS>
      <URL ID="U001">
          <NAME>Google.com</NAME>
          <URLC>http://www.google.com</URLC>
      </URL>
      <URL ID="U002">
          <NAME>Bing.com</NAME>
          <URLC>http://www.bing.com</URLC>
      </URL>
      <URL ID="U003">
          <NAME>Yahoo.com</NAME>
          <URLC>http://www.yahoo.com</URLC>
      </URL>
      <URL ID="U004">
          <NAME>Aol.com</NAME>
          <URLC>http://www.aol.com</URLC>
      </URL>
  </URLS> 
  </COMMUNITY>
</COMMUNITIES>

1 个答案:

答案 0 :(得分:0)

首先,您应该调整获取所需COMMUNITY元素的代码。 xpath方法返回SimpleXMLElement个对象的数组,表示与搜索字符串匹配的元素。

示例:

$returnArray = $nodes->xpath("//COMMUNITY[@ID='$nodeid']"); 
$node = $returnArray[0];

其次,要修改TOP元素的值,请直接设置为TOP本身:

// This replaces the contents of the TOP element with $top
$node->TOP = $top;

// This appends '<nodeValue>$top</nodeValue>' to the contents of TOP
$node->TOP->nodeValue = $top;