您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。