开发者

How to change the value of an xml item using php

I have the following xml file test.xml:

<a>
  <b c="test1" d="test2开发者_如何学Go"/>
  <b c="test3" d="test4"/>
</a>

This xml file can have 1 or more b elements. I would like to ask how could I change the value of item c in a specific b using php.

Thanks in advance.


Using: http://php.net/manual/en/book.dom.php

Sample (all c-attributes):

<?php
$dom = new DomDocument;
$dom->load('sample.xml');

$xpath = new DomXPath($dom);

$cAttribs = $xpath->query('//*[@c]');
foreach ($cAttribs as $entry) {
    $entry->setAttribute('c', 'newValue');
}

header('Content-Type: text/xml; charset="UTF-8"');
echo $dom->saveXml();

Only specific nodes:

$dom = new DomDocument;
$dom->loadXml('<?xml version="1.0" encoding="UTF-8" ?>
<a>
  <b c="test1" d="test2" id="special-case" />
  <b c="test3" d="test4" />
</a>');

$xpath = new DomXPath($dom);

$cAttribs = $xpath->query('//*[@id="special-case"]');
foreach ($cAttribs as $entry) {
    $entry->setAttribute('c', 'newValue');
}

header('Content-Type: text/xml; charset="UTF-8"');
echo $dom->saveXml();


make a ".htaccess" file which is something that controls pages server-side....

add the following line in your page:

AddType application/x-httpd-php .xml

this will make ANY xml document into PHP but if you don't want php in your xml, it's still ok since php is flexible and the page can work without actually having to write php in it.

Now use some str replace to get what you want working...

<?php

$xml = "<a>
  <b c="test1" d="test2"/>
  <b c="test3" d="test4"/>
</a>";

$find = array("test1","test2","test3","test4");

$xml = str_replace($find, "stuff", $xml);

echo $xml;

// output:
// <a>
//   <b c="stuff" d="stuff"/>
//   <b c="stuff" d="stuff"/>
// </a>

?>

I hope this is what you were looking for and I hope it helps...

  • Find out what .htaccess files are
  • Find out how to use str_replace
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜