2013-03-27 141 views
4

我正在嘗試編寫代碼,它將在XML文件中查找特定元素,然後更改文本節點的值。 XML文件具有不同的名稱空間。到目前爲止,我已經設法註冊名稱空間,並且還回顯了我想要更改的元素的文本節點。使用SimpleXML更改文本節點的值使用SimpleXML更改文本節點的值

<?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"; 
    } 
    ?> 

我的問題是:如何使用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> 

感謝 季米特里斯

+0

可能的重複[如何設置SimpleXmlElement的文本值而不使用其父級?](http://stackoverflow.com/questions/3153477/how-can-i-set-text-value-of-simplexmlelement-沒有使用它的父母) – 2017-01-25 10:02:39

回答

1

最後,我成功地做到這一點,通過使用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()); 
    ?> 
-2

你可以這樣說:

$xml->value = "what you want?"; 
+0

似乎沒有工作。 – user1919 2013-03-27 10:08:03

+0

你能給我一個你想改變的xml轉儲的一部分嗎? – Ogelami 2013-03-27 10:09:07

+0

是的。我重新回答了這個問題。 – user1919 2013-03-27 10:15:33