代码之家  ›  专栏  ›  技术社区  ›  Cael

将整数转换为千分隔符时遇到格式不正确的数值

  •  0
  • Cael  · 技术社区  · 10 年前

    我有一个PHP代码来从网站中检索值。我得到了输出,但也收到了通知: 注意:第19行中遇到格式不正确的数值。

    这是我的PHP代码:

    <?php
    header('Content-Type: text/html; charset=utf-8');
    $grep = new DoMDocument();
    @$grep->loadHTMLFile("https://www.postme.com.my/men-1.html");
    
    $finder = new DomXPath($grep);
    $class = "amount";
    
    $nodes = $finder->query("//*[contains(@class, '$class')]");
    
    $i = 0;
      foreach ($nodes as $node) {
        if ($i<1) {
        $span = $node->childNodes;
        $replace = str_replace("Items 1-12 of", "",$span->item(0)->nodeValue);
        echo number_format($replace, 0 , '.' , ',' ) . '<br/>';
      }
       $i++;
      }
    ?>
    

    如何更正它,以便在我为其指定数字格式时通知不会出现。 谢谢

    1 回复  |  直到 10 年前
        1
  •  2
  •   Community    7 年前

    您可以在命令前面放置at符号以忽略所有通知等。这通常是不好的形式,但它应该起作用。

    echo @number_format($replace, 0 , '.' , ',' ) . '<br/>';
    

    编辑:@在错误的位置。

    此外,正如所建议的,您还可以检查以确保值是数字:

    http://php.net/manual/en/function.is-numeric.php

    if(is_numeric($replace){
        echo number_format($replace, 0 , '.' , ',' ) . '<br/>';
    }
    

    编辑编辑:您也可以尝试对变量进行类型转换,如下所述:

    number_format() causes errors in Apache log