从txt中提取值

时间:2016-05-16 23:23:34

标签: php strpos

您好我在太阳能逆变器的Web服务器上有一个txt文件。 这是文件sys.txt的示例: master#0.75kW#24.9#404.1#2630.5#42715.4#0#0#1; 0; 0.33; 9.4; 15555.6; 132; 1#2; 0; 0.15 ; 6.0; 11168.7; 2097185; 3#3; 0; 0.27; 9.4; 15991.0; 2097185; 3#x#

我需要介于#(在这种情况下为0.75 24.9 42715.4)之间的1°,2°,5°数值,即实际功率,每日功率和总功率。我试着写一个PHP脚本,但我无法正确完成它..

/* ########## DATA SUNWAYS ########## */
    $url = “13.3.89.50/data/sys.txt”;
    $username = “customer”;
    $password = “00000000”;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    $output = curl_exec($ch);
    curl_close($ch);

    $actualpower = strpos($output,'/\#(.#?)\#/');   //?????
    $dailypower = strpos($output,'/\#(.#?)\#/');    //?????
    $totalpower = substr($output,'/\#(.#?)\#/' );   //?????
你可以帮帮我吗?

2 个答案:

答案 0 :(得分:0)

您可以使用explode()函数将差异值分隔为#,然后应用filter_var()仅提取数值。

http://php.net/manual/en/function.explode.php

http://php.net/manual/en/function.filter-var.php

http://php.net/manual/en/filter.filters.sanitize.php

所以这应该能满足你的需求:

$input = 'master#0.75kW#24.9#404.1#2630.5#42715.4#0#0#1;0;0.33;9.4;15555.6;132;1#2;0;0.15;6.0;11168.7;2097185;3#3;0;0.27;9.4;15991.0;2097185;3#x#';
$inputArray = explode('#', $input); // get an array with all the separate values

// keep only numeric on the 2nd field (index 1)
$actualPower = filter_var($inputArray[1], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
$dailyPower = filter_var($inputArray[2],FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
$totalPower = filter_var($inputArray[5],FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

echo $actualPower . ' ' . $dailyPower . ' '. $totalPower;

将打印

  

0.75 24.9 42715.4

答案 1 :(得分:0)

这有效:

<?php
$login = 'customer';
$password = '00000000';
$url = 'http://13.3.89.50/data/sys.txt';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$login:$password");
$result = curl_exec($ch);
curl_close($ch);

$results = explode('#', $result);

$actualPower = filter_var($results[1],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
$dailyPower = filter_var($results[2],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
$totalPower = filter_var($results[5],FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
?>