php讀寫json檔案

來源:互聯網
上載者:User

簡介:這是php讀寫json檔案的詳細頁面,介紹了和php,有關的知識、技巧、經驗,和一些php源碼等。

class='pingjiaF' frameborder='0' src='http://biancheng.dnbcw.info/pingjia.php?id=333686' scrolling='no'>

PHP Simple Comments Read/Write jSon data to text file

A few days ago i had to build a simple comment form. First i
thought about MYSQL etc, but this all seems to be too complicated. So i
came up with a simple solution based on jSon and a TXT file.

So that’s how it cooks:

1. Load the text file with the comments and convert it to an array with json_decode

12345
/* get comments from file */$commentsText = file_get_contents('comments.txt'); /* create array list from comments */$commentsList = json_decode($commentsText,true);

2. Check if a new comment was posted and save to file when valid.

12345678910111213141516171819
/* check if new comment is posted and minimum 3 characters are set */if( !empty($_POST['comment']) && strlen($sComment) > 3 ){         /* get posted comment and remove all HTML */        $sComment = strip_tags($_POST['comment']);         /* add comment, client IP and date to array */        $commentsList['comments'][] = array(                'text' => $sComment,                'ip' => $_SERVER['REMOTE_ADDR'],                'date' => time()        );         /* convert comments to string */        $commentsText = json_encode($commentsList);         /* save comment to file */        file_put_contents($commentsFile, $commentsText);}

3. Then we can loop the comment list and create HTML for the output

123456789
/* create html list */$commentsHTML = "<ul>";/* loop all comments */foreach( $commentsList['comments'] as $commentItem ){        // add comment to html list        $commentsHTML.= "<li>" . $commentItem['text'] . "</li>";}/* close html comments list */$commentsHTML .= "</ul>";

4. Then we add the HTML form and the list with comments

1234567
<form id="comments" method="POST"><form id="comments" method="POST">    <h1>Comments?</h2>    <div><?=$errorMessage?></div>    <textarea id="comment" name="comment" cols="70"> </textarea><br/>    <input type="submit" value="yes" />    <?=$commentsHTML?></form>

I know simple but i thought to share it, you can

download
the full example including sorting and some more validation stuff, or check out the example page
.

“php讀寫json檔案”的更多相關文章 》

愛J2EE關注Java邁克爾傑克遜視頻站JSON線上工具

http://biancheng.dnbcw.info/php/333686.html pageNo:11

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.