philipp philipp - 1 month ago 6
PHP Question

BASH–Getting results from PHP

I am trying to retrieve some output from php, using bash. So far I have this:

CODE="<?php chdir('$WWW');" # $WWW should be interpolated

CODE+=$(cat <<'PHP' # no interpolation for the rest of the code
require_once('./settings.php');

$db = $databases['default']['default'];

$out = [
'user=' . $db['username']
//more here
];

echo implode("\n", $out)
PHP)

echo $CODE

#RESULT=$($CODE | php)

#. $RESULT


All in all I am having trouble with the String interpolation. Right now I get:

line 10: <?php: command not found


So how can I properly escape the string such that the whole php code?

All in all, the PHP should generate output like that:

key=value
key2=value2


which can be "sourced" by the bash

Thanks in Ahead!

Answer

Using Here String

php <<< "$CODE"

Using Pipe

echo "$CODE" | php

If you want to store the output into a variable, use the command substitution:

result=$(php <<< "$CODE")
result=$(echo "$CODE" | php)