PHP 从 API 内容创建变量的最佳方式


PHP Best Way to Create Variable from API Content

我是程序员的初学者,我正在学习。如果我的问题太糟糕,我很抱歉。

我想从 api 内容在 php 中创建变量,例如:
此内容来自此 URL:http://example.com/api

{"name":"John","age":"20","genre":"male","language":[{"id":"22","name":"english"},{"id":"23","name":"French"}]}

<?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
?>

我的问题是当我得到一个像"语言"这样的数组时,如何解决它?

感谢您的帮助。

您可以通过两种方式使用该 http://www.php.net/json_decode:

这是面向对象的

$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>';
}

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

正如@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;
    }
?>