5

I am trying to write a code where it will find a specific element in my XML file and then change the value of the text node. The XML file has different namespaces. Till now, I have managed to register the namespaces and also echo the text node of the element, which I want to change.

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

My question is: How can I change the value of this element using SimpleXML? I tried to use the nodeValue command but I am not able to make it work.

This is a part of the 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>

Thanks Dimitris

1

2 Answers 2

1

In the end I managed to do it by using the PHP XML DOM. Here is the code that I used in order to change the text node of a specific element:

  <?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());
  ?>
1

Not wanting to switch from the code I've already made for SimpleXML, I found this solution:

http://www.dotdragnet.com/forum/index.php?topic=3979.0

Specificially:

$numvotes = $xml->xpath('/gallery/image[path="'.$_GET["image"].'"]/numvotes');
...
$numvotes[0][0] = $votes;

Hope this helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.