PHP将发布的数据写入文件

时间:2013-05-29 03:25:11

标签: php vb.net web

我对PHP比较陌生,我正在尝试运行一个小脚本。我有一个VB .net程序,它使用以下函数发布数据。

Public Sub PHPPost(ByVal User As String, ByVal Score As String)
    Dim postData As String = "user=" & User & "&" & "score=" & Score
    Dim encoding As New UTF8Encoding
    Dim byteData As Byte() = encoding.GetBytes(postData)
    Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("http://myphpscript"), HttpWebRequest)
    postReq.Method = "POST"
    postReq.KeepAlive = True
    postReq.ContentType = "application/x-www-form-urlencoded"
    postReq.ContentLength = byteData.Length
    Dim postReqStream As Stream = postReq.GetRequestStream()
    postReqStream.Write(byteData, 0, byteData.Length)
    postReqStream.Close()
End Sub

其中“myphpscript”实际上是PHP脚本的完整URL。基本上我正在尝试将“User”变量和“Score”变量发布到PHP脚本。我试过的脚本如下:

<?php
    $File = "scores.rtf";
    $f = fopen($File,'a');
    $name = $_POST["name"];
    $score = $_POST["score"];
    fwrite($f,"\n$name $score");
    fclose($f);
?>

“scores.rtf”不会改变。任何帮助,将不胜感激。提前谢谢,我是PHP的新手。

2 个答案:

答案 0 :(得分:0)

  

“scores.rtf”不会改变。

RTF文件的处理方式不同,因为它不是纯粹的文本文件,它包含控制文本在rtf文件上的显示方式的元数据和标记。请有时间阅读以下来源

http://www.webdev-tuts.com/generate-rtf-file-using-php.html

http://b-l-w.de/phprtf_en.php

http://paggard.com/projects/doc.generator/doc_generator_help.html

如果您想要普通文本文件,可以使用下面的代码,请不要使用fwrite(),请使用file_put_contents()

file_put_contents("scores.txt", "\n$name $score");

答案 1 :(得分:0)

确保您的脚本正在接收POST变量。

http://php.net/manual/en/function.file-put-contents.php

你可以试试file_put_contents,它结合了fopen,fwrite和amp;的使用。 FCLOSE。

使用像isset / empty这样的东西来检查写作之前是否有东西是明智的。

<?php
$file = 'scores.rtf';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= print_r($_POST);

//Once confirmed remove the above line and use below
$current .= $_POST['name'] . ' ' . $_POST['score'] . "\n";

// Write the contents back to the file
file_put_contents($file, $current);
?>

另外,完全忽略了RTF部分,一定要看看Mahan提到的内容。如果您不需要特定的文件类型,我建议您使用上述内容。

相关问题