如果XML标记值与PHP相同的XML中的另一个标记值相匹配,则乘以XML标记值

时间:2019-03-20 21:03:59

标签: php xml dom simplexml

我一直在阅读有关如何将XML标记值与相同XML中的另一个标记的值相匹配的方法进行乘法,我举一个例子:

我有一个具有以下值的XML:

<?xml version="1.0" encoding="utf-8"?>
<products>
  <item>
    <name>PRODUCT 1</name>
    <brand>BRAND 1</brand>
    <currency>CURRENCY 1</currency>
    <price>10</price>
  </item>
  <item>
    <name>PRODUCT 2</name>
    <brand>BRAND 2</brand>
    <currency>CURRENCY 1</currency>
    <price>5</price>
  </item>
  <item>
    <name>PRODUCT 3</name>
    <brand>BRAND 3</brand>
    <currency>CURRENCY 2</currency>
    <price>1</price>
  </item>
  <item>
    <name>PRODUCT 4</name>
    <brand>BRAND 4</brand>
    <currency>CURRENCY 2</currency>
    <price>2</price>
  </item>
  <item>
    <name>PRODUCT 5</name>
    <brand>BRAND 5</brand>
    <currency>CURRENCY 2</currency>
    <price>5</price>
  </item>
</products>

如果与<price>标记中的CURRENCY 2匹配,我需要将<currency>标记中的值乘以10,从而得到类似以下结果:

<?xml version="1.0" encoding="utf-8"?>
<products>
  <item>
    <name>PRODUCT 1</name>
    <brand>BRAND 1</brand>
    <currency>CURRENCY 1</currency>
    <price>10</price>
  </item>
  <item>
    <name>PRODUCT 2</name>
    <brand>BRAND 2</brand>
    <currency>CURRENCY 1</currency>
    <price>5</price>
  </item>
  <item>
    <name>PRODUCT 3</name>
    <brand>BRAND 3</brand>
    <currency>CURRENCY 2</currency>
    <price>10</price><!--- Have been multiplied by 10 because matched "CURRENCY 2" on the "<currecy>" tag -->
  </item>
  <item>
    <name>PRODUCT 4</name>
    <brand>BRAND 4</brand>
    <currency>CURRENCY 2</currency>
    <price>20</price><!--- Have been multiplied by 10... -->
  </item>
  <item>
    <name>PRODUCT 5</name>
    <brand>BRAND 5</brand>
    <currency>CURRENCY 2</currency>
    <price>50</price><!--- Have been multiplied by 10... -->
  </item>
</products>

我写了这段代码,但是它不起作用,我不确定为什么,任何帮助将不胜感激。

<?php
$sXML = simplexml_load_file('file.xml', null, LIBXML_NOBLANKS);
$currency = $sXML->xpath("//item[currency='CURRENCY 2']");
foreach ( $currency as $value )    {
    $value = $value * 10;
}
unset($value);

$domDocument = dom_import_simplexml($sXML)->ownerDocument;
$domDocument->formatOutput = true;
echo $domDocument->save('new.xml');
?>

1 个答案:

答案 0 :(得分:0)

由于使用了这种sintax $value->price = $value->price * 10

<?php
$sXML = simplexml_load_file('file.xml', null, LIBXML_NOBLANKS);
$currency = $sXML->xpath("//item[currency='CURRENCY 2']");
foreach ( $currency as $value )    {
    $value->price = $value->price * 10;
}
unset($value);

$domDocument = dom_import_simplexml($sXML)->ownerDocument;
$domDocument->formatOutput = true;
echo $domDocument->save('new.xml');
?>