URL和JSON常见操作函数练习

Original 2019-06-21 07:45:26 219
abstract:1、代码<?php //七、其他常用字符串函数 //1.urlencode($url):就是在特殊字符前面加%,防止服务器解析出现歧义 $url = 'http://www.ifeng.com'; echo $url,'<br>'; $url = urlencode('http://www

1、代码

<?php
//七、其他常用字符串函数
//1.urlencode($url):就是在特殊字符前面加%,防止服务器解析出现歧义
$url = 'http://www.ifeng.com';
echo $url,'<br>';

$url = urlencode('http://www.ifeng.com');

echo $url,'<br>';
//http_build_query($arr):生成url动态查询字符串
$url = urldecode($url);
echo '<a href="'.$url.'">凤凰网</a>','<br>';

//2.http_build_query()生成动态查询字符串
// ?p=5
// cate_id=10&art_id=15
echo http_build_query(['cate_id'=>10,'art_id'=>15]),'<br>';

//3.parse_url() 解析url
$url = 'http://www.ifeng.com/article.html?p=5';
$url = parse_url($url);
echo '<pre>',var_export($url,true),'<hr>';

//json相关的函数
//二个约定:1.必须是utf8编码,2,不能处理资源类型:resource
//1.json_encode():将数据进行json编码,转为json格式
//2.json_decode():将json格式的字符串解析还原为变量

//1.json_encode()
//变量
$name = '张三';
echo json_encode($name),'<br>';

//数组[身高,体重,年龄]
$res = ['height'=>175,'weight'=>65,'age'=>20];
echo json_encode($res),'<br>';

//对象格式
$obj = new stdClass();
$obj->name = '李四';
$obj->sex =  '男';
$obj->res = ['height'=>180,'weight'=>75,'age'=>25];
echo json_encode($obj),'<br>';
echo '<hr>';

//2.json_decode():默认返回的都是对象
$json ='{"height":190,"weight":80,"age":30}';
$res = json_decode($json);
echo gettype($res),'<br>';
echo '体重是:',$res->weight,'<br>';

//以数组方式返回
$res = json_decode($json,true);
echo gettype($res),'<br>';
echo '身高是:',$res['height'],'<br>';

2、浏览器

QQ截图20190621074508.jpg

Correcting teacher:天蓬老师Correction time:2019-06-21 09:56:56
Teacher's summary:json目前已经是最流行的前后端的数据交互格式了, 每一种编程语言都提供了大量的针对json格式数据的处理函数....

Release Notes

Popular Entries