Home > OS >  How to select ID by changing xml file with PHP
How to select ID by changing xml file with PHP

Time:02-12

I’m trying to change an XML file by PHP. It’s working but I can’t find how I can select the specific ID. any ideas? For example, I would like to change the text of id ken1. Thanks in advance!

PHP:

    <form method="post">
  <input name="ken1" id="ken1" type="text">
  <br>
  <input type="submit" name="submit" value="submit">
</form>

<?php

if(isset($_POST['submit'])) {

$data=simplexml_load_file('display.xml');
$data->data->SText->ken1->text=$_POST['ken1'];

$handle=fopen("display.xml","wb");
fwrite($handle,$data->asXML());
fclose($handle);
}

$data=simplexml_load_file('display.xml');
?>

xml:

<kendisplay>

  <meta>
    <request>setData</request>
    <version>1</version>
  </meta>
  <data>
    <SText id="p1">
      <text>test</text>
    </SText>
    <SText id="p2">
      <text>test</text>
    </SText>
    <SText id="ken1">
      <text>test</text>
    </SText>
    <SText id="wait">
      <text>test</text>
    </SText>
  </data>

</kedisplay>

CodePudding user response:

So to actually use the xpath to update the document:

// assume $data has the fully parsed SimpleXMLElement document, as in the original post.
echo $data->asXML();
$ken = $data->xpath("//SText[@id='ken1']");
$ken[0]->text = "updated";
echo $data->asXML(); 

And output:

(First echo of original)

<?xml version="1.0"?>
<kendisplay>
<meta>
<request>setData</request>
<version>1</version>
</meta>
<data>
<SText id="p1">
<text>test</text>
</SText>
<SText id="p2">
<text>test</text>
</SText>
<SText id="ken1">
<text>test</text>
</SText>
<SText id="wait">
<text>test</text>
</SText>
</data>
</kendisplay>

(And second echo with updated value)

<?xml version="1.0"?>
<kendisplay>
<meta>
<request>setData</request>
<version>1</version>
</meta>
<data>
<SText id="p1">
<text>test</text>
</SText>
<SText id="p2">
<text>test</text>
</SText>
<SText id="ken1">
<text>updated</text>
</SText>
<SText id="wait">
<text>test</text>
</SText>
</data>
</kendisplay>

Remember the xpath returns an array of 0 or more SimpleXMLElements which satisfy the path query. So be sure to handle that appropriately.

  • Related