Php To Json如何转换?

时间:2015-05-29 19:31:54

标签: php json

我们可以将php代码转换为json格式吗? 我可能没有准确的PHP编码我是初学者,因为我是新手。我将集成到Android应用程序中。 我还画了一些关于信息的图片?

例如,我想做这样的事情:http://mikepenz.com/android/unsplash/pictures

<?php
// don't forget to change 'username' to your actual tumblr name
$request = 'http://walltumbler.tumblr.com/api/read/json';
$ci = curl_init($request);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
$input = curl_exec($ci);
// Tumblr JSON doesn't come in standard form, some str replace needed
$input = str_replace('var tumblr_api_read = ','',$input);
$input = str_replace(';','',$input);
// parameter 'true' is necessary for output as PHP array
$value = json_decode($input, true);
$content =  $value['posts'];
// the number of items you want to display
$item = 98988;
// Tumblr provides various photo size, this case will choose the 75x75 square one
$type = 'photo-url-1280';


?>
{
    "limit": null,
    "offset": 0,
    "count": 2442,
    "total": 2442,
    "data": [

<?php

for ($i=0;$i<=$item;$i++) {
    if ($content[$i]['type'] == 'photo') {
        echo '
          {
            "id": '.$i.';
            "author": "Paul Jarvis",
            "image_src": "' . $content[$i][$type] . '",
            "color": "#7F7873",
            "date": "2015-01-21 19:20:00",
            "modified_date": "2014-09-01 22:36:53",
            "width": 2500,
            "height": 1667,
            "ratio": 1.4997000694275,
            "featured": 1,
            "temp_id": 1
        }';
      $string = rtrim($item, ', ');
    }
}
?>
]}

1 个答案:

答案 0 :(得分:0)

尝试使用json_encode()功能

<?php

$request = 'http://walltumbler.tumblr.com/api/read/json';
$ci = curl_init($request);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
$input = curl_exec($ci);
$input = str_replace('var tumblr_api_read = ','',$input);
$input = str_replace(';','',$input);
$value = json_decode($input, true);
$content =  $value['posts'];
$item = 98988;
$type = 'photo-url-1280';

$photos_array = array();

for ($i=0;$i<=$item;$i++) {
    if ($content[$i]['type'] == 'photo') {
        $photos_array[] = array(
            'id' => $i,
            'author' => 'Paul Jarvis',
            // Continue with all your values...
        );
    }
}

$json_data = array(
    'limit'  => null,
    'offset' => 0,
    'count'  => 2442,
    'total'  => 2442,
    'data'   => $photos_array
);

// Then use json_encode to get your json data...

echo json_encode( $json_data );

希望有所帮助