我是程序员的初学者,我正在学习。 如果我的问题太糟糕,我很抱歉。
我想从api内容中创建php中的变量,例如:
此内容来自以下网址:http://example.com/api
{"名称":"约翰""年龄":" 20""类型":& #34;男性""语言":[{" ID":" 22""名称":"英语"},{" ID":" 23""名称":"法国"}]}
<?php
$content = file_get_contents("http://example.com/api");
$content = str_replace('"', "", $content);
$content = str_replace(":", "=", $content);
$content = str_replace(",", "&", $content);
parse_str($content);
echo $name; //John
echo $age; //20
echo $genre; //male
echo $language //[{id <======== here is my problem
?>
我的问题是当我得到像#34;语言&#34;这样的数组时,如何修复它?
感谢您的帮助。
答案 0 :(得分:2)
你可以通过两种方式使用Screenshot:
这是对象导向:
$str = '{"name":"John","age":"20","genre":"male","language":[{"id":"22","name":"english"},{"id":"23","name":"french"}]}';
$json = json_decode($str);
echo 'name: ' . $json->{'name'} .'<br>';
echo 'age: ' . $json->{'age'} .'<br>';
echo 'genre: ' . $json->{'genre'} . '<br>';
foreach($json->{'language'} as $data){
echo 'id: ' . $data->{'id'} . '<br>';
echo 'name: ' . $data->{'name'} . '<br>';
}
作为关联数组:
$json = json_decode($str, true);
echo 'name: ' . $json['name'] .'<br>';
echo 'age: ' . $json['age'] .'<br>';
echo 'genre: ' . $json['genre'] . '<br>';
foreach($json['language'] as $data){
echo 'id: ' . $data['id'] . '<br>';
echo 'name: ' . $data['name'] . '<br>';
}
答案 1 :(得分:1)
正如@fusionK所指出的,来自api请求的响应是一个json字符串,所以使用json_decode
(json_decode( $data,true )
为数组)转换为对象(或首选数组)
解码后,可以直接访问对象的属性。
<?php
/* capture and decode response from api - creates an object */
$content = json_decode( file_get_contents("http://example.com/api") );
/* using object notation to access properties */
echo $content->name.' '.$content->age.' '.$content->genre;
/* for the language which is an array of objects */
$lang=$content->language;
foreach( $lang as $language ){
$obj=(object)$language;
echo $obj->id.' '.$obj->name;
}
?>
答案 2 :(得分:1)
json_decode()
将帮助您将字符串数据转换为更易于访问的内容:
<?php
// Instead of your fetched data we use static example data in this script
//$content = file_get_contents("http://example.com/api");
$content = '{"name":"John","age":"20","genre":"male","language":[{"id":"22","name":"english"},{"id":"23","name":"french"}]}';
// Convert json data to object
$data = json_decode($content);
// access object properties by using "->" operator
echo $data->name;
echo $data->age;
echo $data->genre;
// language is an array of objects, so let's look at each language object...
foreach($data->language as $lang) {
// ... and extract data using "->" again
echo $lang->id;
echo $lang->name;
}
可以在http://sandbox.onlinephpfunctions.com/code/6df679c3faa8fff43308a34fb80b2eeb0ccfe47c
找到此代码的实例