LoginSignup
0
1

More than 3 years have passed since last update.

PHP ファイルの内容を書き込み、読み込み

Last updated at Posted at 2020-08-28

ファイルの書き込み

file_put_contents("ファイルの場所","書き込みたい内容");
file_put_contentsは戻り値を持つためif文でチェック可能

qiita.php
<?php
    $check = file_put_contents("news_data/php_lesson.text","2020-08-28,ファイルの書き込み");
    if ($check){
        print ("書き込み完了");
    }else{
        print ("書き込みエラー");
    }
    ?>

ファイルの読み込み

file_fet_contentsの戻り値が読み込んだデータとなる

qiita.php
<?php
    $check = file_get_contents("news_data/news.text");
    print ($check);
    ?>

read_fileでは戻り値をprintしなくても出力できる
この場合は、読み取ったデータを加工できない

qiita.php
<?php
    readfile("news_data/news.text");
    ?>

データの追加

.=とすると文字列の後に追加される

qiita.php
<?php
    $news = file_get_contents("news_data/news.text");
    $news .= "追加データ";
    file_put_contents("news_data/news.text",$news);
    print ($news)
    ?>

文字列の前に追加したい場合

qiita.php
<?php
    $news = file_get_contents("news_data/news.text");
    $news = "追加データ".$news;
    file_put_contents("news_data/news.text",$news);
    print ($news)
    ?>

XMLの情報を読み込む

XMLとは

XMLは、文章の見た目や構造を記述するためのマークアップ言語の一種です。
拡張できる様々な分野で利用可能。
一般的にはRSS(更新情報)で利用されている。

qiita.php
<?php
    $xmlTree = simplexml_load_file('http://nakata.net/feed/');

    foreach ($xmlTree->channel->item as $item):
        ?><a href="<?php print($item->link); ?>"><?php print($item->title); ?></a>

    <?php
    endforeach;
    ?>

プロパティの関係はこのようになっており、
->で中の要素にアクセスしていく
itemは配列になっているため$itemで格納していく

<channel>
<item>
<title></title>
<link></link>
</item>
</channel>

JSON

JSONとはJavaScript Object Notationの略で、XMLなどと同様のテキストベースのデータフォーマットです。
短くかけてわかりやすいため、JavaScriptに限らず使われている。

jsonの内容がget_contentsのあと
decodeする事でPHPのオブジェクト化できる
xmlとjsonでは構造が異なる

qiita.php
 <?php
    $file = file_get_contents('https://h2o-space.com/feed/json/');
    $json =json_decode($file);

    foreach ($json-> items as $item):
        ?><a href="<?php print($item->url); ?>"><?php print($item->title); ?></a>

    <?php
    endforeach;
    ?>
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1