Linux下C/C++代码调用PHP代码(转)

Linux下C/C++代码可以通过popen系统函数调用PHP代码并通过fgets函数获取PHP代码echo输出的字符串。

  1. //main.c  
  2.     char str[1024] = {0};  
  3.     char * cmd = "php /src/test/c.php 1234";  
  4.     FILE * stream = NULL;  
  5.     if ((stream = popen(cmd, "r")) == NULL){//通过popen执行PHP代码  
  6.         return "";  
  7.     }  
  8.     std::string ret = "";  
  9.     while((fgets(str, 1024, stream)) != NULL){//通过fgets获取PHP中echo输出的字符串  
  10.         ret += str;  
  11.     }  
  12.     pclose(stream);  
  13.     return ret;  
//main.c
	char str[1024] = {0};
	char * cmd = "php /src/test/c.php 1234";
	FILE * stream = NULL;
	if ((stream = popen(cmd, "r")) == NULL){//通过popen执行PHP代码
		return "";
	}
	std::string ret = "";
	while((fgets(str, 1024, stream)) != NULL){//通过fgets获取PHP中echo输出的字符串
		ret += str;
	}
	pclose(stream);
	return ret;

    其中,cmd的“1234”是传递给php文件的参数。PHP代码中,可以和普通的C语言中的main函数一样,通过argc和argv这2个参数来获取这个参数“1234”。

  1. // /src/test/c.php  
  2. <?php  
  3. include_once(dirname(__FILE__).'/m.php');  
  4. include_once(dirname(__FILE__).'/m/SpsTable.php');  
  5.   
  6. if ($argc != 2){ //和C/C++的main函数一样,参数有2个,第一个是php文件名,第二个是main.c中cmd字符串中的“1234”  
  7.     die();  
  8. }  
  9.   
  10. array_shift($argv);//移除第一个参数,第一个参数是php文件名  
  11.   
  12. $spsFileId = (int)$argv[0];  
// /src/test/c.php
<?php
include_once(dirname(__FILE__).'/m.php');
include_once(dirname(__FILE__).'/m/SpsTable.php');

if ($argc != 2){ //和C/C++的main函数一样,参数有2个,第一个是php文件名,第二个是main.c中cmd字符串中的“1234”
	die();
}

array_shift($argv);//移除第一个参数,第一个参数是php文件名

$spsFileId = (int)$argv[0];

    PHP代码中需要注意的是,如果被调用的PHP文件有include额外的PHP文件,最好通过dirname(__FILE__)或其他方法使用PHP文件的绝对路径,否则很容易出现找不到PHP文件的错误。

http://blog.csdn.net/liuyangwuhan1980/article/details/41745041

原文地址:https://www.cnblogs.com/xihong2014/p/8028032.html