您好,登錄后才能下訂單哦!
printf
是一個用于格式化字符串的 PHP 語言函數
<?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"])
);
?>
在構建 API 響應時,使用 printf
可以幫助你快速生成格式化的字符串,從而提高開發效率。同時,通過設置正確的 Content-Type
頭,你可以確保客戶端能夠正確解析響應數據。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。