我正在尝试使用 php 脚本来查询 mysql 数据库,使用数据创建一个 xml 文件,然后将其返回以在 C++ 应用程序中访问。然后我将尝试编辑 C++ 返回的数据,例如打印或截断它。现在我在 C++ 中的主要函数中所拥有的只是
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
cout << system("C:/xampp/php/php E:/phpTest.php");
return 0;
}
我的 php 脚本包括...
phpTest.pnp:
<?php
require_once("mysqli.php");
$connector = new Mysqli_connector();
$xmlTest = $connector->selectTest();
return $xmlTest;
?>
和 mysqli.php:
<?php
class Mysqli_connector {
var $conn;
function __construct($db=array()) {
$default = array(
'host' => 'hostname',
'user' => 'username',
'pass' => 'password',
'db' => 'database'
);
$db = array_merge($default,$db);
$this->conn = mysqli_connect($db['host'],$db['user'],$db['pass'],$db['db'])
or die("Error connecting to database");
}
function __destruct() {
mysqli_close($this->conn);
}
function selectTest(){
$res = mysqli_query($this->conn,"select * from loginTest") or die("Error querying");
$xml_output = "<?xml version=\"1.0\"?>\n";
$xml_output .= "<Data>" . "\n";
$xml_output .= "field1" ."\t". "field2" ."\t". "field3" ."\t". "field4" ."\t". "field5";
$xml_output .= "\n";
for($x = 0; $x < mysqli_num_rows($res); $x++)
{
$row = mysqli_fetch_assoc($res);
$xml_output .= $row['field1'] . "\t";
$xml_output .= $row['field2'] . "\t";
$xml_output .= $row['field3'] . "\t";
$xml_output .= $row['field4'] . "\t";
$xml_output .= $row['field5'] . "\n";
}
return $xml_output;
}
}
?>
当我从 mysqli.php 返回时,使用 return
似乎确实有效,但随后我无法使用相同的 return 语句将其发送到 C++ 应用程序。有谁知道正确的方法吗?
最佳答案
正如您上面的评论所说,将 return
更改为 echo
。任何 PHP 脚本的顶层(例如,函数调用之外)都不是函数,并且无处可返回。换句话说,没有什么“更高”的东西可以捕获您返回的值,因此脚本只是退出。
更改为 echo
会强制实际输出 XML,这将由您的 C++ 应用程序捕获。
例如如果您的脚本是:
<?php
echo 'foo';
return 'bar';
您的 C++ 应用程序将看到 foo
返回,而不是 foobar
- 返回值丢失,因为没有函数调用返回 FROM。
关于php - 将 XML 从 php 返回到 C++ 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20958392/