1 minute read

学んだこと

少数の切り上げ・切り捨て・四捨五入

  • 小数の切り捨て
    • floor を使用
  • 小数の切り上げ
    • ceil を使用
  • 四捨五入
    • round を使用
      • 第二引数に、四捨五入を行う桁数を指定する。戻り値に四捨五入された値が出力される。
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sample01</title>
</head>
<body>
    3000円から100円引きした場合、
    <?php echo floor(100 / 3000 * 100); ?>%引き

    <br>
    <?php echo ceil(3.33);?><br>
    <?php echo round(3.66, 1);?><br>

</body>
</html>

文字列のフォーマットを整える

  • sprintf を使って文字列のフォーマットを整える。  - C++や C#と同じように sprintf の戻り値のフォーマットを決められる。  - 例えば、整数で 4 桁にしたい場合は%04d、小数は%f、文字列であれば%s など。
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sample01</title>
</head>
<body>
    <?php
    $date = sprintf('%04d.%02d.%02d', 2021, 8, 3);
    echo $date
    ?>
</body>
</html>

ファイルに書き込む

  • file_put_contents を使うことで、ファイルに書き込む事ができる。
    • file_put_contents の第二引数は、ファイル内に何を書き込むかを指定する。
  • file_put_contents の戻り値が false の場合は、ファイルに書き込めていない。そのため、file_put_contents の戻り値を変数に格納し、if 文でエラーチェックすることを推奨する。
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sample01</title>
</head>
<body>
    <?php
    $success = file_put_contents('data/news.txt', 'ホームページをリニューアルしました。');
    if($success){
        echo 'ファイルの書き込みが完了しました。';
    }else{
        echo 'ファイルの書き込みが失敗しました。';
    }
    ?>
</body>
</html>

ファイルを読み込む

  • file_get_contents や readfile を使ってファイルを読み込む事ができる。
    • file_get_contents
      • 戻り値に読み込んだ文字列を返す。
    • readfile
      • 画面に読み込んだ文字列を出力する。
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sample01</title>
</head>
<body>
    <?php
    $news = file_get_contents('data/news.txt');
    echo $news;

    // この関数でもファイルの読み込みができる
    readfile('data/news.txt');
    ?>
</body>
</html>

XML ファイルを読み込む

  • simplexml_load_file を使うことで、XML 形式のファイルを読み込む事ができる。
    • XML オブジェクトが戻り値として設定される。
    • XML オブジェクト->タグ名でタグ内の要素にアクセスすることができる。
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sample01</title>
</head>
<body>
    <?php
    $xmlTree = simplexml_load_file('rss.xml');
    foreach ($xmlTree->channel->item as $item):
    ?>
    ・<a href="<?php echo $item->link ?>"><?php echo $item->title ?><br>
    <?php endforeach;?>

</body>
</html>

Tags:

Updated: