Intereting Posts

从node.js发送请求到PHP,返回一个数组

我有一个我想要访问的名为'name_scraper'的SQL表,并检索设置范围之间的数据,然后返回结果数组到我的node.js文件以供使用。 从本质上讲,Node js请求,PHP $ _GET [''],mysqli_query,然后呢?

这是我的节点js代码来联系php文件

var request = require('request'); var http = require('http'); var post_options = { host: 'localhost', path: '/name_request.php?pos1=0&pos2=5', method: 'POST', headers: { 'User-Agent': 'Super Agent/0.0.1', 'Content-Type': 'application/x-www-form-urlencoded', } }; var post_req = http.request(post_options, function (res) { res.on('data', function (chunk) { console.log('Response: ' + chunk); chnk = chunk; console.log("chunk: " +chnk[0]); //random test I did that doesn't work }); }); post_req.end(); 

现在上面的代码在联系我的PHP文件,然后输出数组到控制台。

这是我的PHP:

 $servername = "localhost"; //localhost $username = "root"; $password = ""; $dbname = "test"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $start = $_GET['pos1']; $end = $_GET['pos2']; $sql = mysqli_query($conn, "SELECT * FROM name_scraper WHERE ID BETWEEN '$start' AND '$end'"); $array = mysqli_fetch_all($sql); print_r($array); //can change to specific index and it works fine ?> 

这整体pipe理检索数据,但不返回数据在一个可用的forms,该数组不是一个数组返回,只是响应的一部分。 我需要它以可用的forms返回数组,所以我可以操作和提取每个索引内的数据。

Solutions Collecting From Web of "从node.js发送请求到PHP,返回一个数组"

你应该改变你的输出方法,如下所示;

 $sql = mysqli_query($conn, "SELECT * FROM name_scraper WHERE ID BETWEEN '$start' AND '$end'"); $array = mysqli_fetch_all($sql,MYSQLI_ASSOC); //If you add MYSQLI_ASSOC your output will be better echo json_encode($array); //That will output an json array 

希望这可以帮助