使用php中的多个子节点更新XML的节点值

时间:2014-05-13 11:56:38

标签: php xml xpath

以下是我的XML文件,我想更新在latestBid中的doller和cent值。我首先尝试了玩偶值,但它不起作用。我甚至试图更新描述('//item[id="4"]/description'),即使这不起作用。请告诉我我在这里做错了什么。 XML档案

<?xml version="1.0"?>
<items>
  <item>
    <itemNumber>4</itemNumber>
    <latestBid>
      <latestCustomerId>1</latestCustomerId>
      <bidPrice>
        <doller>2342</doller>
        <cent>23</cent>
      </bidPrice>
    </latestBid>
  </item>
  <item>
    <itemNumber>5</itemNumber>
    <latestBid>
      <latestCustomerId>1</latestCustomerId>
      <bidPrice>
        <doller>35345</doller>
        <cent>78</cent>
      </bidPrice>
    </latestBid>
  </item>
</items>

PHP档案

<?php
$url = '../../data/auction2.xml';
$itemNumber ="4";
$bidDoller = 45;
$bidCent=55;
$doc = new DomDocument();
$xml=simplexml_load_file($url);
//echo "came 1";working
foreach ($xml->xpath('//item[@itemNumber="4"]/latestBid/bidPrice/doller') as $desc) {
  echo "came 2";//nt working
  $dom=dom_import_simplexml($desc);
  $dom->nodeValue = $bidDoller; 
  }
file_put_contents($url, $xml->asXML()); 
?>

编辑。仍然没有工作

2 个答案:

答案 0 :(得分:1)

谢谢你们每个人通过编辑和回答获得支持我终于做到了。因为我这样做并不容易,所以我发布答案来帮助像我这样的人:)。 我没有改变xml。

php文件

$url = '../../data/auction2.xml';

$itemNumber ="4";
$bidDoller = 85;
$bidCent=95;

$xml=simplexml_load_file($url);
$resultDoller= $xml->xpath('//item[itemNumber="'.$itemNumber.'"]/latestBid/bidPrice/doller');
$resultCent= $xml->xpath('//item[itemNumber="'.$itemNumber.'"]/latestBid/bidPrice/cent');

$resultDoller[0][0]=$bidDoller;
$resultCent[0][0]=$bidCent;
print $xml->asXML();

file_put_contents($url, $xml->asXML()); 

答案 1 :(得分:0)

以下为我工作, // XML

<?xml version="1.0"?>
<items>
  <item id="4">
    <itemNumber>4</itemNumber>
    <latestBid>
      <latestCustomerId>1</latestCustomerId>
      <bidPrice>
        <doller>2342</doller>
        <cent>23</cent>
      </bidPrice>
    </latestBid>
  </item>
  <item>
    <itemNumber>5</itemNumber>
    <latestBid>
      <latestCustomerId>1</latestCustomerId>
      <bidPrice>
        <doller>35345</doller>
        <cent>78</cent>
      </bidPrice>
    </latestBid>
  </item>
</items>

// PHP

<?php
$url = '../../data/auction2.xml';
$itemNumber ="4";
$bidDoller = 45;
$bidCent=55;
$doc = new DomDocument();
$xml=simplexml_load_file($url);
$result = $xml->xpath('//item[@id="4"]/latestBid/bidPrice/doller');

echo "<pre>";
print_r($result);
//echo "came 1";working
foreach ($xml->xpath('//item[@id="4"]/latestBid') as $desc) {
  echo "came 2";//nt working
  $dom=dom_import_simplexml($desc);
  $dom->nodeValue = $bidDoller; 
  }
//file_put_contents($url, $xml->asXML()); 
?>