Windows VistaVisual Studio .NET 2003Windows 2003.NET 1.1Windows 2000Windows XPPHP中级开发Visual StudioWindows.NETC#
PHP4Apps:从您的应用程序进行 PHP 脚本编写






4.19/5 (9投票s)
2005年12月20日
2分钟阅读

87715

937
如何从您的应用程序调用PHP引擎并接收回复和任何变量。
引言
通常,在.NET中运行PHP脚本需要调用操作系统并将响应管道输送回来。借助Serhiy Perevoznyk的PHP4Delphi,Delphi开发人员能够利用Zend(PHP)引擎,而无需诉诸shell。 Serhiy创建了一个非托管DLL,您可以从.NET调用它,以获得使用脚本引擎的好处。如果您是Delphi开发人员,则可以从SourceForge的PHP4Delphi项目下获取包装器的完整源代码。
背景
如果您不熟悉PHP,它是一种非常流行的Web脚本语言,类似于Perl和Python。与这些语言一样,它也适用于桌面以及Web。
此包装器构建在PHP引擎之上,提供与php4ts.dll(对于PHP版本4)或php5ts.dll的接口。您将需要此文件才能使用php4apps.dll。我已将此文件包含在演示下载中,但最新版本可从PHP项目站点获得。
使用代码
包装器DLL中公开了七个方法
InitRequest
- 初始化引擎。ExecutePHP
- 使用要运行的文件调用引擎。ExecuteCode
- 使用要运行的字符串调用引擎。GetResultText
- 从引擎检索脚本的结果。RegisterVariable
- 向引擎注册变量,允许您稍后检索该值。GetVariable
- 在引擎完成后检索已注册变量的值。DoneRequest
- 完成引擎。
执行文件的简单方法如下
// Initialize the Request
int RequestID = InitRequest();
// Execute the engine
ExecutePHP(RequestID, openFileDialog1.FileName);
// Create a buffer for the reply
StringBuilder builder = new StringBuilder();
// Call it once to get the length
builder.Capacity = GetResultText(RequestID, builder, 0);
// Call it a second time to get the value
GetResultText(RequestID, builder, builder.Capacity + 1);
// Finalize the engine
DoneRequest(RequestID);
与此类似,评估字符串只需将ExecutePHP
方法替换为ExecuteCode
方法
...
string code = "phpInfo();";
ExecuteCode(RequestID, code);
...
请注意,您不需要PHP代码周围的<? ?>
。如果需要,您可以包含它。
现在,有趣的部分是您可以注入自己的变量并检索结果。如果PHP代码如下所示
$i="Hello ".$i;
print $i;
如果要更改$i
的值,而不必将值附加到脚本,则可以使用RegisterVariable
在执行前设置变量
string code = "$i=\"Hello \".$i; print $i;";
// Initialize the Request
int RequestID = InitRequest();
// Execute the engine
ExecuteCode(RequestID, code);
// Register a variable with the engine
RegisterVariable(RequestID, "i", "World!");
现在,结果将是必需的“Hello World!”。要从引擎检索$i
的值,您只需要调用GetVariable
。
// Create a buffer for the variable reply
StringBuilder resultVariable = new StringBuilder();
// Call it once to get the length
resultVariable.Capacity = GetVariable(RequestID, "i", resultVariable, 0);
// Call it a second time to actually get the value
GetVariable(RequestID, "i", resultVariable, resultVariable.Capacity+1);
历史
- 1.0 - 初始版本。