Inserting Python code with PHP variables inside EOT

I am trying to create a Python script from PHP. PHP script injects variables into python code and then outputs the resulting python script.

Using <<<EOT

, it should read php variables, leaving any others (e.g. python related)

 // PHP Var
        $date = '12/04/2017';
        $id = '2';
        $phparray['value1'] = '03:45';
        $phparray['value2'] = '08:00';
        $phparray['value3'] = '17:00';
        $phparray['value4'] = '21:30';

// Embed Variables in the Python script code to be later generated  

        $PythonContents =  <<<EOT
    I'm, trying to embed "$phpvar" inside python code.

    '''
    Python script generated on {$date}

    '''

    # Python Function specific imports
    import datetime

    ################    Python configs ############
    myvar = 'fixed'  
    function_id   = {$id}  
    Python-With-PHP-var-Range = [['{$phparray['value1']}','{$phparray['value2']}'],['{$phparray['value3']}','{$phparray['value4']}']]

Result-IN-Python-range = [['03:45','08:00'],['17:00','21:30']]

Python-and-PHP-var2 = {
             '{$generateID}/f/{$data_sensor['device_id']}/test/{$data['heatControlRelay']}/rstate': 'heatingisLocked',
              }
ResultINPython = {
              '44/f/folder1/test/85111': 'Value',
             }
################    End of Python config     #############################
################    Python script below     #############################

################    End of Python script   #############################


                EOT;
echo $PythonContents;

      

+3


source to share


1 answer


A major cliff with an extra spacing before the end EOT

, but also full undefined vars.

So this is fixed:



<?php
// PHP Var
$generateID = '123';

$data_sensor['device_id'] = 'xyz';
$data['heatControlRelay'] = '12345';

$date = '12/04/2017';
$id = '2';
$phparray['value1'] = '03:45';
$phparray['value2'] = '08:00';
$phparray['value3'] = '17:00';
$phparray['value4'] = '21:30';

// Embed Variables in the Python script code to be later generated  
$PythonContents =  <<<EOT
    I'm, trying to embed "\$phpvar" inside python code.

    '''
    Python script generated on {$date}

    '''

    # Python Function specific imports
    import datetime

    ################    Python configs ############
    myvar = 'fixed'  
    function_id   = {$id}  
    Python-With-PHP-var-Range = [['{$phparray['value1']}','{$phparray['value2']}'],['{$phparray['value3']}','{$phparray['value4']}']]

    Result-IN-Python-range = [['03:45','08:00'],['17:00','21:30']]

    Python-and-PHP-var2 = {
        '{$generateID}/f/{$data_sensor['device_id']}/test/{$data['heatControlRelay']}/rstate': 'heatingisLocked',
    }

    ResultINPython = {
        '44/f/folder1/test/85111': 'Value',
    }
EOT;
echo $PythonContents;

      

+3


source







All Articles