百分比的负整数

时间:2009-11-13 10:28:47

标签: php regex

我有很多文件包含使用基本数学函数转换为百分比的数据:

<param id="1" name="otb" value="0.160"/>
<param id="2" name="blm" value="-0.210"/>
<param id="3" name="mep" value="-0.010"/>
<param id="4" name="plc" value="-0.100"/>

每个id都是它自己的等式:

  1. (N - ( - 3))/ 2.3 * 100
  2. (N - ( - 8))/ 3.3 * 100
  3. (N - ( - 5))/ 1.5 * 100
  4. (N - (1))/ 1.1 * 100
  5. 所以我得到了:

    OTB = 8  BLM = 20  MEP = 24  PLC = 0

    通过...正则表达式和PHP运行所有这些文件的好方法是什么?那里有快速而又脏的代码吗? :d

2 个答案:

答案 0 :(得分:1)

由于文件似乎是XML格式,我建议你试试PHP simplexml库。可以找到文档here

然后,您只需访问XML对象的魔术属性即可访问XML树:

$xml = simplexml_load_file('your/path/to/your/file');

foreach ($xml->param as $param)
{
    $id = $param['id'];
    $name = $param['name'];
    $value = $param['value'];

    // do your calculations...
}

答案 1 :(得分:0)

样式表魔术:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
  <xsl:output indent="yes" standalone="yes" omit-xml-declaration="yes" method="xml"/>
  <xsl:template match="*">
    <xsl:copy>
      <xsl:variable name="Values" select="@*[(name(..)='param') and ((name(.)='value'))]"/>
      <xsl:variable name="NonValues" select="@*[. != $Values]"/>
      <xsl:apply-templates select="$NonValues" mode="NonValues"/>
      <xsl:apply-templates select="$Values" mode="Values"/>
      <xsl:choose>
        <xsl:when test="*">
          <xsl:apply-templates select="*"/>
        </xsl:when>
        <xsl:otherwise>
          <xsl:value-of select="."/>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="@*" mode="Values">
    <xsl:attribute name="value"><xsl:variable name="n" select="."/><xsl:choose><xsl:when test="../@id=1"><xsl:value-of select="(($n - (-0.3)) div 2.3) * 100"/></xsl:when><xsl:when test="../@id=2"><xsl:value-of select="(($n - (-0.8)) div 3.3) * 100"/></xsl:when><xsl:when test="../@id=3"><xsl:value-of select="(($n - (-0.5)) div 1.5) * 100"/></xsl:when><xsl:when test="../@id=4"><xsl:value-of select="(($n - (0.1)) div 1.1) * 100"/></xsl:when><xsl:otherwise><xsl:value-of select="."/></xsl:otherwise></xsl:choose></xsl:attribute>
  </xsl:template>
  <xsl:template match="@*" mode="NonValues">
    <xsl:copy>
      <xsl:value-of select="(.)*2"/>pp
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

如果您可以使用此样式表转换原始XML,您将获得包含计算结果的新XML。它有点复杂,但基本上代码处理所有元素和子元素。对于每个元素,它将属性向上拆分为需要转换的值和其他值。它复制除value属性之外的每个元素,每个子元素和每个属性。处理值属性并给出另一个值。 (但是如果你想保留它,你也可以添加原始值。)