phpしっかり入門教室(ファイルを読込 URLの読込)

file_get_contents() を使ったURLの読み込み例

以下は指定したURLからテキストを読み込む例です。


file_get_contents(URL)

Hello, this is a sample text file.
This file is used to demonstrate reading content from a URL using PHP.
Enjoy coding!


        ここまでのコードでphpについて説明できますか



        sample.txtファイルを以下の内容で作成し、ウェブサーバー上の適切な場所((https://canape.stars.ne.jp/10/p/sample.txt)にアップロードします。)

   コード内容
            Hello, this is a sample text file.
            This file is used to demonstrate reading content from a URL using PHP.
            Enjoy coding!

        
sample.php内のphpコード部分
        <?php
        // URLからデータを読み込む
        $url = "https://canape.stars.ne.jp/10/p/sample.txt";
        $contents = file_get_contents($url);

        if ($contents !== false) {
            echo nl2br(htmlspecialchars($contents));
        } else {
            echo "URLの内容を読み込むことができませんでした。";
        }
        ?>
             PHPコードを含むファイルを作成し、ウェブサーバー上に配置します。
        ブラウザでそのPHPファイルにアクセスすると、sample.txtの内容が表示されるはずです。
        この方法で、ウェブ上のテキストファイルの内容をPHPを使って簡単に取得し表示することがで