๋น๋๊ธฐ์ฒ๋ฆฌ? ๋๊ธฐ์ฒ๋ฆฌ?
์ด๋ฏธ ์ ๋ณด๋ค ํ๋ฅญํ์ ๋ถ๋ค์ด ์ค๋ช ํด ์ฃผ์ค ๊ฑฐ๋ผ ๋ฏฟ์ด ๋ฐ๋ก ์ค๋ช ํ์ง ์๊ฒ ๋ค.
PHP์ JS๋ก ๋น๋๊ธฐ ์ฒ๋ฆฌ ๊ตฌํํ๊ธฐ
index.html
document.addEventListener("DOMContentLoaded", function () {
fetch("get_lunch.php")
.then(response => response.text())
.then(data => {
document.getElementById("lunch-info").innerHTML = data;
});
});
์ด๋ฒคํธ๋ฆฌ์ค๋๋ก DOMContentLoaded๋ฅผ ํตํด ๋ํธ๋ฆฌ๊ฐ ๋ค ๋ฐ์๋๋ค๋ฉด ์คํ๋๋ ์ฝ๋์ด๋ค. load ์ด๋ฒคํธ์ ์ฐจ์ด์ ์ load ์ด๋ฒคํธ๋ HTML์ ์์๋ค์ด ๋ค ๋ก๋๊ฐ ๋ ํ ์คํ๋๋ ๋ฐ๋ฉด, DOMContentLoaded ์ด๋ฒคํธ๋ ๋ํธ๋ฆฌ๋ง ๋ฐ์๋๋ฉด ์คํ๋๋ค.
load ์ด๋ฒคํธ๋ฅผ ์ฌ์ฉํ ๋ HTML์ ๋ก๋๊ฐ ์ค๋ ๊ฑธ๋ฆฐ๋ค๋ฉด ๊ทธ๋งํผ ์คํ์ด ๋ฆ๊ฒ ๋๊ธฐ ๋๋ฌธ์ ์ฌ๋งํด์๋ DOMContentLoaded๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์ ์ถ์ฒํ๋ค.
get_lunch.php
<?php
include "db.php";
$ATPT_OFCDC_SC_CODE = 'K10';
$SD_SCHUL_CODE = '7801093';
$API_KEY = 'shinee_key';
function lunchExport($date)
{
global $ATPT_OFCDC_SC_CODE;
global $SD_SCHUL_CODE;
global $API_KEY;
$apiUrl = "https://open.neis.go.kr/hub/mealServiceDietInfo?ATPT_OFCDC_SC_CODE={$ATPT_OFCDC_SC_CODE}&SD_SCHUL_CODE={$SD_SCHUL_CODE}&MLSV_YMD={$date}&KEY={$API_KEY}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$xml = new SimpleXMLElement($response);
$rows = $xml->xpath("//row");
if (count($rows) === 0) {
$mealName = "๋ฑ๋ก๋ ๊ธ์ ์ ๋ณด๊ฐ ์์ต๋๋ค.";
} else {
$mealNames = [];
foreach ($rows as $row) {
$mealName = (string)$row->DDISH_NM;
$mealName = preg_replace('/[^\p{Hangul}<>br]+/u', '', $mealName);
$mealNames[] = $mealName;
}
$mealName = "<div class='row'><div class='col-5'><b>์ค์</b><br>" . implode("</div><div class='col-5'><b>์์</b><br>", $mealNames) . "</div></div>";
}
return $mealName;
}
echo lunchExport(date('Ymd'));
?>
fetch๋ก PHP API๋ฅผ ๋ถ๋ฌ์ค๋๋ฐ, echo ํ์์ผ๋ก PHP์์ ๋ฐ์ดํฐ๊ฐ์ ๋ณด๋ด๊ฒ ๋๋ค. ๊ทธ ํ, JS์ fetch์์ get_lunch.php์ ๋ฐ์ดํฐ๋ฅผ text ํ์์ผ๋ก ๋ฐ์ ์ถ๋ ฅํ๊ฒ ๋๋ค.
์ด๋ ๊ฒ ๋๋ฉด DOMContentLoaded๋ก ๋ํธ๋ฆฌ๊ฐ ๋ก๋ ๋ ํ, PHP API๋ฅผ ํตํด ๋ฐ์ดํฐ๋ฅผ ๋ฐ์์ค๊ฒ ๋์ด ๋น๋๊ธฐ ๋ฐฉ์์ผ๋ก ์ฒ๋ฆฌํ๊ฒ ๋๋ค.