1

Due to some reasons in need to run a small part of my NodeJS Project in PHP7. I know I can make an internal API but that would increase network dependency.

To solve this problem I found that this can be done as

php test.php

How do I provide a JSON input to this PHP file where data is stored in a JS variable not in file and receive output in another JS variable.

function runPHP(jsonString){
    ....what to write here
    ...
    return output_string;
}

Note: Please, do not suggest Query parameters as the data is too large.

1 Answer 1

1

I assume you want to call a php scipt from a nodejs process, send some arguments in JSON and get back some JSON and process it further.

The php script:

<?php
// test.php
$stdin = fopen('php://stdin', 'r');

$json = '';

while ($line = fgets($stdin)) {
    $json .= $line;
}

$decoded = \json_decode($json);

$decoded->return_message = 'Hello from PHP';

print \json_encode($decoded);

exit(0);

The nodejs script:

// test.js
function runPHP(jsonString) {
  const spawn = require('child_process').spawn;
  const child = spawn('php', ['test.php']);

  child.stdin.setEncoding('utf-8');
  child.stdout.pipe(process.stdout);

  child.stdin.write(jsonString + '\n');

  child.stdin.end();
}

runPHP('{"message": "hello from js"}');

This will need some polishing and error handling...

Sign up to request clarification or add additional context in comments.

1 Comment

This is more than what need to start. :) Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.