Php 使用SimpleXML更改文本节点的值

Php 使用SimpleXML更改文本节点的值,php,simplexml,Php,Simplexml,我正在尝试编写一个代码,它将在XML文件中找到一个特定元素,然后更改文本节点的值。XML文件具有不同的名称空间。到目前为止,我已经成功地注册了名称空间,还回显了元素的文本节点,我想对其进行更改 <?php $xml = simplexml_load_file('getobs.xml'); $xml->registerXPathNamespace('g','http://www.opengis.net/gml'); $result = $xml->x

我正在尝试编写一个代码,它将在XML文件中找到一个特定元素,然后更改文本节点的值。XML文件具有不同的名称空间。到目前为止,我已经成功地注册了名称空间,还回显了元素的文本节点,我想对其进行更改

   <?php

   $xml = simplexml_load_file('getobs.xml');

   $xml->registerXPathNamespace('g','http://www.opengis.net/gml');

   $result = $xml->xpath('//g:beginPosition');


   foreach ($result as $title) {
   echo $title . "\n";
   }
   ?>
registerXPathNamespace('g','http://www.opengis.net/gml');
$result=$xml->xpath('//g:beginPosition');
foreach($result作为$title){
回显$title。“\n”;
}
?>
我的问题是:如何使用SimpleXML更改此元素的值?我尝试使用nodeValue命令,但无法使其工作

这是XML的一部分:

        <sos:GetObservation xmlns:sos="http://www.opengis.net/sos/1.0"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" service="SOS" version="1.0.0"  srsName="urn:ogc:def:crs:EPSG:4326">
          <sos:offering>urn:gfz:cawa:def:offering:meteorology</sos:offering>
            <sos:eventTime>
              <ogc:TM_During xmlns:ogc="http://www.opengis.net/ogc" xsi:type="ogc:BinaryTemporalOpType">
              <ogc:PropertyName>urn:ogc:data:time:iso8601</ogc:PropertyName>
                <gml:TimePeriod xmlns:gml="http://www.opengis.net/gml">
                  <gml:beginPosition>2011-02-10T01:10:00.000</gml:beginPosition>

urn:gfz:cawa:def:provide:气象学
urn:ogc:data:time:iso8601
2011-02-10T01:10:00.000
谢谢
Dimitris

最后,我通过使用PHP XML DOM实现了这一点。 以下是我用来更改特定元素的文本节点的代码:

  <?php
  // create new DOM document and load the data
  $dom = new DOMDocument;
  $dom->load('getobs.xml');
  //var_dump($dom);
  // Create new xpath and register the namespace
  $xpath = new DOMXPath($dom);
  $xpath->registerNamespace('g','http://www.opengis.net/gml');
  // query the result amd change the value to the new date
  $result = $xpath->query("//g:beginPosition");
  $result->item(0)->nodeValue = 'sds';
  // save the values in a new xml
  file_put_contents('test.xml',$dom->saveXML());
  ?>
registerNamespace('g','http://www.opengis.net/gml');
//查询结果并将值更改为新日期
$result=$xpath->query(“//g:beginPosition”);
$result->item(0)->nodeValue='sds';
//将值保存在新的xml中
文件内容('test.xml',$dom->saveXML());
?>

不想从我为SimpleXML编写的代码中切换,我找到了以下解决方案:

具体而言:

$numvotes = $xml->xpath('/gallery/image[path="'.$_GET["image"].'"]/numvotes');
...
$numvotes[0][0] = $votes;
希望这有帮助

可能重复的