You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将php_execute_script()的输出存储到字符数组中?

捕获php_execute_script()的输出到C字符数组

方法一:通过PHP脚本的输出缓冲传递结果

在PHP脚本中利用输出缓冲函数捕获自身输出,将结果存入变量后,在C代码中读取该变量即可。

首先修改say.php:

<?php
// 开启输出缓冲
ob_start();

// 脚本原有逻辑,比如输出内容
echo "Hello from embedded PHP!";

// 捕获缓冲内容并清空缓冲
$output = ob_get_clean();
?>

然后调整C代码:

PHP_EMBED_START_BLOCK(argc, argv)

char string[200] = {0}; // 初始化数组避免垃圾值
zend_file_handle file_handle;
zend_stream_init_filename(&file_handle, "say.php");

if (php_execute_script(&file_handle) == FAILURE) {
    php_printf("Failed to execute PHP script.\n");
} else {
    zval *output_zval;
    // 从PHP全局符号表读取$output变量
    if (zend_hash_find(&EG(symbol_table), "output", sizeof("output") - 1, (void**)&output_zval) == SUCCESS) {
        // 验证变量类型为字符串后安全复制到C数组
        if (Z_TYPE_P(output_zval) == IS_STRING) {
            strncpy(string, Z_STRVAL_P(output_zval), sizeof(string) - 1);
        }
    }
}

printf("\"%s\" is what say.php has to say.\n", string);

PHP_EMBED_END_BLOCK()

方法二:在C层替换PHP输出处理回调

利用PHP嵌入API提供的php_output_set_handler函数,自定义输出处理回调,直接将PHP输出写入C字符数组。

先定义回调函数(放在C嵌入代码块之外):

static int capture_output(const char *buffer, uint32_t length, void *user_data) {
    char *target = (char*)user_data;
    // 安全拼接内容,避免数组溢出
    size_t current_len = strlen(target);
    if (current_len + length < sizeof(target)) {
        strncat(target, buffer, length);
    }
    return length;
}

再修改C嵌入代码:

PHP_EMBED_START_BLOCK(argc, argv)

char string[200] = {0};
zend_file_handle file_handle;
zend_stream_init_filename(&file_handle, "say.php");

// 设置自定义输出回调,将输出写入string数组
php_output_set_handler(capture_output, string, PHP_OUTPUT_HANDLER_STDFLAGS);

if (php_execute_script(&file_handle) == FAILURE) {
    php_printf("Failed to execute PHP script.\n");
}

// 结束所有输出缓冲,确保内容全部被捕获
php_output_end_all();

printf("\"%s\" is what say.php has to say.\n", string);

PHP_EMBED_END_BLOCK()

原方法无效的原因

PHP嵌入SAPI拥有独立的输出管理机制,php_execute_script的输出会先经过PHP自身的输出缓冲层处理,不会直接写入C标准输出stdout,因此直接用setbuf重定向C的stdout无法捕获这部分内容,必须通过PHP提供的输出控制接口处理。

内容的提问来源于stack exchange,提问作者user14719210

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 10:25:03