Monday, February 2, 2009

C#: Reading output from PHP

Steps (MS Visual C#):



  1. Create a new Console Application

  2. Declare four variables req, response, output and reader as WebRequest, WebResponse, Stream and StreamReader

  3. Create an web request using WebRequset.Create(string url)
    (e.g. req = WebRequest.Create(http://localhost/index.php);)

  4. Set WebRequest method as POST
    (req.Method = "POST");

  5. Set :
    response = req.GetResponse();
    output = response.GetResponseStream();
    reader = new StreamReader(output);

  6. Now reader has the output from the PHP file

  7. To read from the reader, reader.ReadLine() method can be used

Example:


(C# : phpEchoReader.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;


namespace phpEchoReader {
class Program {
static void Main(string[] args) {
WebRequest req;
WebResponse response;
Stream output;
StreamReader reader;
req =
WebRequest.Create("http://localhost/index.php");
req.Method = "POST";
response = req.GetResponse();
output = response.GetResponseStream();
reader = new StreamReader(output);
while (!reader.EndOfStream)
{
Console.WriteLine(reader.ReadLine());
}
Console.WriteLine("Press any key too continue...");
Console.ReadLine();
}
}
}


(php code: index.php)

for ($i = 0; $i <>

echo $i."\n";

?>


Output:


No comments:

Post a Comment