您好,登錄后才能下訂單哦!
printf
是一個用于格式化字符串的 PHP 語言函數(shù)
<?php
$data = array(
"name" => "John Doe",
"age" => 30,
"city" => "New York"
);
header('Content-Type: application/json');
echo printf(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
?>
<?php
$data = array(
"user" => array(
"id" => 1,
"name" => "John Doe",
"email" => "john.doe@example.com"
)
);
header('Content-Type: application/xml');
echo printf(xml_encode($data, XML_PRETTY_PRINT | XML_USE_CDATA));
?>
<?php
$data = array(
array("Name", "Age", "City"),
array("John Doe", 30, "New York"),
array("Jane Smith", 28, "Los Angeles")
);
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="data.csv"');
$fp = fopen('php://output', 'w');
foreach ($data as $row) {
fputcsv($fp, $row);
}
fclose($fp);
?>
<?php
$data = array(
"name" => "John Doe",
"age" => 30,
"city" => "New York",
"is_student" => false,
"courses" => array("PHP", "MySQL", "JavaScript")
);
header('Content-Type: text/plain');
echo printf("%s is %d years old and lives in %s. %s is a student. He is studying the following courses: %s.\n",
$data["name"],
$data["age"],
$data["city"],
$data["is_student"] ? "Yes" : "No",
implode(", ", $data["courses"])
);
?>
在構(gòu)建 API 響應(yīng)時,使用 printf
可以幫助你快速生成格式化的字符串,從而提高開發(fā)效率。同時,通過設(shè)置正確的 Content-Type
頭,你可以確保客戶端能夠正確解析響應(yīng)數(shù)據(jù)。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。