Search code examples
phpstrpos

extract values from txt


Hi i have a txt file on a web server of a solar inverter. This is an example of the file 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#

I need the 1°,2°,5° numeric value that is between # ( in this case 0.75 24.9 42715.4 ) that are actual power, daily power and total power. I tried to write a php script but I can't finish it properly..

/* ########## 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,'/\#(.#?)\#/' );   //?????

can you help me?


Solution

  • You can use the explode() function to separate the differents value by #, then apply filter_var() to extract only numeric values.

    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

    So this should achieve your needs:

    $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;
    

    Will print

    0.75 24.9 42715.4