在 PHP 中为 JSON return 创建对象的 table

Make table of object in PHP for JSON return

我正在使用这个脚本来制作 json :

<?php
header('Content-Type: application/json');
$feed = new DOMDocument();
$feed->load("http://www.feedforall.com/sample.xml");
//$feed->load($_GET['url']);
$json = array();

$json['title'] =  $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$json['description'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
$json['link'] =  $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('link')->item(0)->firstChild->nodeValue;

$items = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('item');

$json['item'] = array();
$i = 0;


foreach($items as $item) {

   $title =  $item->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
   $description = $item->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
   $pubDate = $item->getElementsByTagName('pubDate')->item(0)->firstChild->nodeValue;
   $guid = $item->getElementsByTagName('guid')->item(0)->firstChild->nodeValue;

   $json['item'][$i++]['title'] = $title;
   $json['item'][$i++]['description'] = $description;
   $json['item'][$i++]['pubdate'] = $pubDate;
   $json['item'][$i++]['guid'] = $guid;   

}


echo json_encode($json);


?>

在 foreach 循环中,它把 feed 的所有项目一个接一个地放入项目 php table.

当我return时,没有table,所有物品属性都平发:

{
    "title": "FeedForAll Sample Feed",
    "description": "RSS is a fascinating technology. The uses for RSS are expanding daily. Take a closer look at how various industries are using the benefits of RSS in their businesses.",
    "link": "http://www.feedforall.com/industry-solutions.htm",
    "item": [
        {
            "title": "RSS Solutions for Restaurants"
        },
        {
            "description": "<b>FeedForAll </b>helps Restaurant's communicate with customers. Let your customers know the latest specials or events.<br>\n<br>\nRSS feed uses include:<br>\n<i><font color=\"#FF0000\">Daily Specials <br>\nEntertainment <br>\nCalendar of Events </i></font>"
        },
        {},
        {},
        {
            "title": "RSS Solutions for Schools and Colleges"
        },
        {
            "description": "FeedForAll helps Educational Institutions communicate with students about school wide activities, events, and schedules.<br>\n<br>\nRSS feed uses include:<br>\n<i><font color=\"#0000FF\">Homework Assignments <br>\nSchool Cancellations <br>\nCalendar of Events <br>\nSports Scores <br>\nClubs/Organization Meetings <br>\nLunches Menus </i></font>"
        },
        {
            "pubdate": "Tue, 19 Oct 2004 11:09:09 -0400"
        },
        {
            "guid": null
        },
        {
            "title": "RSS Solutions for Computer Service Companies"
        },
        {
            "description": "FeedForAll helps Computer Service Companies communicate with clients about cyber security and related issues. <br>\n<br>\nUses include:<br>\n<i><font color=\"#0000FF\">Cyber Security Alerts <br>\nSpecials<br>\nJob Postings </i></font>"
        },
        {
            "pubdate": "Tue, 19 Oct 2004 11:09:07 -0400"
        },
        {
            "guid": null
        },
        {
            "title": "RSS Solutions for Governments"
        },
        {
            "description": "FeedForAll helps Governments communicate with the general public about positions on various issues, and keep the community aware of changes in important legislative issues. <b><i><br>\n</b></i><br>\nRSS uses Include:<br>\n<i><font color=\"#00FF00\">Legislative Calendar<br>\nVotes<br>\nBulletins</i></font>"
        },
        {
            "pubdate": "Tue, 19 Oct 2004 11:09:05 -0400"
        },
        {
            "guid": null
        },
        {
            "title": "RSS Solutions for Politicians"
        },
        {
            "description": "FeedForAll helps Politicians communicate with the general public about positions on various issues, and keep the community notified of their schedule. <br>\n<br>\nUses Include:<br>\n<i><font color=\"#FF0000\">Blogs<br>\nSpeaking Engagements <br>\nStatements<br>\n </i></font>"
        },
        {
            "pubdate": "Tue, 19 Oct 2004 11:09:03 -0400"
        },
        {
            "guid": null
        },
        {
            "title": "RSS Solutions for Meteorologists"
        },
        {
            "description": "FeedForAll helps Meteorologists communicate with the general public about storm warnings and weather alerts, in specific regions. Using RSS meteorologists are able to quickly disseminate urgent and life threatening weather warnings. <br>\n<br>\nUses Include:<br>\n<i><font color=\"#0000FF\">Weather Alerts<br>\nPlotting Storms<br>\nSchool Cancellations </i></font>"
        },
        {
            "pubdate": "Tue, 19 Oct 2004 11:09:01 -0400"
        },
        {
            "guid": null
        },
        {
            "title": "RSS Solutions for Realtors & Real Estate Firms"
        },
        {
            "description": "FeedForAll helps Realtors and Real Estate companies communicate with clients informing them of newly available properties, and open house announcements. RSS helps to reach a targeted audience and spread the word in an inexpensive, professional manner. <font color=\"#0000FF\"><br>\n</font><br>\nFeeds can be used for:<br>\n<i><font color=\"#FF0000\">Open House Dates<br>\nNew Properties For Sale<br>\nMortgage Rates</i></font>"
        },
        {
            "pubdate": "Tue, 19 Oct 2004 11:08:59 -0400"
        },
        {
            "guid": null
        },
        {
            "title": "RSS Solutions for Banks / Mortgage Companies"
        },
        {
            "description": "FeedForAll helps <b>Banks, Credit Unions and Mortgage companies</b> communicate with the general public about rate changes in a prompt and professional manner. <br>\n<br>\nUses include:<br>\n<i><font color=\"#0000FF\">Mortgage Rates<br>\nForeign Exchange Rates <br>\nBank Rates<br>\nSpecials</i></font>"
        },
        {
            "pubdate": "Tue, 19 Oct 2004 11:08:57 -0400"
        },
        {
            "guid": null
        },
        {
            "title": "RSS Solutions for Law Enforcement"
        },
        {
            "description": "<b>FeedForAll</b> helps Law Enforcement Professionals communicate with the general public and other agencies in a prompt and efficient manner. Using RSS police are able to quickly disseminate urgent and life threatening information. <br>\n<br>\nUses include:<br>\n<i><font color=\"#0000FF\">Amber Alerts<br>\nSex Offender Community Notification <br>\nWeather Alerts <br>\nScheduling <br>\nSecurity Alerts <br>\nPolice Report <br>\nMeetings</i></font>"
        },
        {
            "pubdate": "Tue, 19 Oct 2004 11:08:56 -0400"
        },
        {
            "guid": null
        }
    ]
}

那么错误是什么?我在想把 tables 放在项目中的事实应该有效,但显然不行:-/ 我怎样才能让它们看起来更像这个项目中的项目?

{
    "status": "ok",
    "feed": {
        "url": "http://www.feedforall.com/sample.xml",
        "title": "FeedForAll Sample Feed",
        "link": "http://www.feedforall.com/industry-solutions.htm",
        "author": "",
        "description": "RSS is a fascinating technology. The uses for RSS are expanding daily. Take a closer look at how various industries are using the benefits of RSS in their businesses.",
        "image": "http://www.feedforall.com/ffalogo48x48.gif"
    },
    "items": [
        {
            "title": "RSS Solutions for Restaurants",
            "pubDate": "2004-10-19 15:09:11",
            "link": "http://www.feedforall.com/restaurant.htm",
            "guid": "db4b074250d7eedba34de1c872724ebd",
            "author": "",
            "thumbnail": "",
            "description": "\n<b>FeedForAll </b>helps Restaurant's communicate with customers. Let your customers know the latest specials or events.<br><br>\nRSS feed uses include:<br><i>Daily Specials <br>\nEntertainment <br>\nCalendar of Events </i>\n",
            "content": "\n<b>FeedForAll </b>helps Restaurant's communicate with customers. Let your customers know the latest specials or events.<br><br>\nRSS feed uses include:<br><i>Daily Specials <br>\nEntertainment <br>\nCalendar of Events </i>\n",
            "enclosure": [],
            "categories": [
                "Computers/Software/Internet/Site Management/Content Management"
            ]
        },
        {
            "title": "RSS Solutions for Schools and Colleges",
            "pubDate": "2004-10-19 15:09:09",
            "link": "http://www.feedforall.com/schools.htm",
            "guid": "315ce482517f7e1d2d50f5a68d0e64fc",
            "author": "",
            "thumbnail": "",
            "description": "FeedForAll helps Educational Institutions communicate with students about school wide activities, events, and schedules.<br><br>\nRSS feed uses include:<br><i>Homework Assignments <br>\nSchool Cancellations <br>\nCalendar of Events <br>\nSports Scores <br>\nClubs/Organization Meetings <br>\nLunches Menus </i>\n",
            "content": "FeedForAll helps Educational Institutions communicate with students about school wide activities, events, and schedules.<br><br>\nRSS feed uses include:<br><i>Homework Assignments <br>\nSchool Cancellations <br>\nCalendar of Events <br>\nSports Scores <br>\nClubs/Organization Meetings <br>\nLunches Menus </i>\n",
            "enclosure": [],
            "categories": [
                "Computers/Software/Internet/Site Management/Content Management"
            ]
        },
        {
            "title": "RSS Solutions for Computer Service Companies",
            "pubDate": "2004-10-19 15:09:07",
            "link": "http://www.feedforall.com/computer-service.htm",
            "guid": "7973f3583dd2e760f6e1385a90cf87a8",
            "author": "",
            "thumbnail": "",
            "description": "FeedForAll helps Computer Service Companies communicate with clients about cyber security and related issues. <br><br>\nUses include:<br><i>Cyber Security Alerts <br>\nSpecials<br>\nJob Postings </i>\n",
            "content": "FeedForAll helps Computer Service Companies communicate with clients about cyber security and related issues. <br><br>\nUses include:<br><i>Cyber Security Alerts <br>\nSpecials<br>\nJob Postings </i>\n",
            "enclosure": [],
            "categories": [
                "Computers/Software/Internet/Site Management/Content Management"
            ]
        },
        {
            "title": "RSS Solutions for Governments",
            "pubDate": "2004-10-19 15:09:05",
            "link": "http://www.feedforall.com/government.htm",
            "guid": "d6131efb3d938b112ab861b97434942a",
            "author": "",
            "thumbnail": "",
            "description": "FeedForAll helps Governments communicate with the general public about positions on various issues, and keep the community aware of changes in important legislative issues. <b><i><br></i></b><br>\nRSS uses Include:<br><i>Legislative Calendar<br>\nVotes<br>\nBulletins</i>\n",
            "content": "FeedForAll helps Governments communicate with the general public about positions on various issues, and keep the community aware of changes in important legislative issues. <b><i><br></i></b><br>\nRSS uses Include:<br><i>Legislative Calendar<br>\nVotes<br>\nBulletins</i>\n",
            "enclosure": [],
            "categories": [
                "Computers/Software/Internet/Site Management/Content Management"
            ]
        },
        {
            "title": "RSS Solutions for Politicians",
            "pubDate": "2004-10-19 15:09:03",
            "link": "http://www.feedforall.com/politics.htm",
            "guid": "d01522b2d34449e665339b1c64500492",
            "author": "",
            "thumbnail": "",
            "description": "FeedForAll helps Politicians communicate with the general public about positions on various issues, and keep the community notified of their schedule. <br><br>\nUses Include:<br><i>Blogs<br>\nSpeaking Engagements <br>\nStatements<br></i>\n",
            "content": "FeedForAll helps Politicians communicate with the general public about positions on various issues, and keep the community notified of their schedule. <br><br>\nUses Include:<br><i>Blogs<br>\nSpeaking Engagements <br>\nStatements<br></i>\n",
            "enclosure": [],
            "categories": [
                "Computers/Software/Internet/Site Management/Content Management"
            ]
        },
        {
            "title": "RSS Solutions for Meteorologists",
            "pubDate": "2004-10-19 15:09:01",
            "link": "http://www.feedforall.com/weather.htm",
            "guid": "5273191196b584a4c5a98017d5a1b1d6",
            "author": "",
            "thumbnail": "",
            "description": "FeedForAll helps Meteorologists communicate with the general public about storm warnings and weather alerts, in specific regions. Using RSS meteorologists are able to quickly disseminate urgent and life threatening weather warnings. <br><br>\nUses Include:<br><i>Weather Alerts<br>\nPlotting Storms<br>\nSchool Cancellations </i>\n",
            "content": "FeedForAll helps Meteorologists communicate with the general public about storm warnings and weather alerts, in specific regions. Using RSS meteorologists are able to quickly disseminate urgent and life threatening weather warnings. <br><br>\nUses Include:<br><i>Weather Alerts<br>\nPlotting Storms<br>\nSchool Cancellations </i>\n",
            "enclosure": [],
            "categories": [
                "Computers/Software/Internet/Site Management/Content Management"
            ]
        },
        {
            "title": "RSS Solutions for Realtors &amp; Real Estate Firms",
            "pubDate": "2004-10-19 15:08:59",
            "link": "http://www.feedforall.com/real-estate.htm",
            "guid": "ce3eb8e9a2370c05babd1f4d67796e03",
            "author": "",
            "thumbnail": "",
            "description": "FeedForAll helps Realtors and Real Estate companies communicate with clients informing them of newly available properties, and open house announcements. RSS helps to reach a targeted audience and spread the word in an inexpensive, professional manner. <br><br>\nFeeds can be used for:<br><i>Open House Dates<br>\nNew Properties For Sale<br>\nMortgage Rates</i>\n",
            "content": "FeedForAll helps Realtors and Real Estate companies communicate with clients informing them of newly available properties, and open house announcements. RSS helps to reach a targeted audience and spread the word in an inexpensive, professional manner. <br><br>\nFeeds can be used for:<br><i>Open House Dates<br>\nNew Properties For Sale<br>\nMortgage Rates</i>\n",
            "enclosure": [],
            "categories": [
                "Computers/Software/Internet/Site Management/Content Management"
            ]
        },
        {
            "title": "RSS Solutions for Banks / Mortgage Companies",
            "pubDate": "2004-10-19 15:08:57",
            "link": "http://www.feedforall.com/banks.htm",
            "guid": "548e21e2baaba66f6cf56a92d72fa85a",
            "author": "",
            "thumbnail": "",
            "description": "FeedForAll helps <b>Banks, Credit Unions and Mortgage companies</b> communicate with the general public about rate changes in a prompt and professional manner. <br><br>\nUses include:<br><i>Mortgage Rates<br>\nForeign Exchange Rates <br>\nBank Rates<br>\nSpecials</i>\n",
            "content": "FeedForAll helps <b>Banks, Credit Unions and Mortgage companies</b> communicate with the general public about rate changes in a prompt and professional manner. <br><br>\nUses include:<br><i>Mortgage Rates<br>\nForeign Exchange Rates <br>\nBank Rates<br>\nSpecials</i>\n",
            "enclosure": [],
            "categories": [
                "Computers/Software/Internet/Site Management/Content Management"
            ]
        },
        {
            "title": "RSS Solutions for Law Enforcement",
            "pubDate": "2004-10-19 15:08:56",
            "link": "http://www.feedforall.com/law-enforcement.htm",
            "guid": "6e4ab6d2fee3c163f22e07ac8df11421",
            "author": "",
            "thumbnail": "",
            "description": "\n<b>FeedForAll</b> helps Law Enforcement Professionals communicate with the general public and other agencies in a prompt and efficient manner. Using RSS police are able to quickly disseminate urgent and life threatening information. <br><br>\nUses include:<br><i>Amber Alerts<br>\nSex Offender Community Notification <br>\nWeather Alerts <br>\nScheduling <br>\nSecurity Alerts <br>\nPolice Report <br>\nMeetings</i>\n",
            "content": "\n<b>FeedForAll</b> helps Law Enforcement Professionals communicate with the general public and other agencies in a prompt and efficient manner. Using RSS police are able to quickly disseminate urgent and life threatening information. <br><br>\nUses include:<br><i>Amber Alerts<br>\nSex Offender Community Notification <br>\nWeather Alerts <br>\nScheduling <br>\nSecurity Alerts <br>\nPolice Report <br>\nMeetings</i>\n",
            "enclosure": [],
            "categories": [
                "Computers/Software/Internet/Site Management/Content Management"
            ]
        }
    ]
}

您每 属性 增加一次计数器。由于它设置为 0 开始,所以你应该只在最后这样做:

$json['item'][$i++]['title'] = $title;
$json['item'][$i++]['description'] = $description;
$json['item'][$i++]['pubdate'] = $pubDate;
$json['item'][$i++]['guid'] = $guid; 

应该是:

$json['item'][$i]['title'] = $title;
$json['item'][$i]['description'] = $description;
$json['item'][$i]['pubdate'] = $pubDate;
$json['item'][$i]['guid'] = $guid; 
# Increment the counter for the next iteration
$i++;

您每次添加新项目时都会递增 $i。试试这个:

$json['item'][$i++] = array(
  'title' => $title,
  'description' => $description,
  'pubdate' => $pubDate,
  'guid' => $guid,
);

或者:

$json['item'][$i]['title'] = $title;
$json['item'][$i]['description'] = $description;
$json['item'][$i]['pubdate'] = $pubDate;
$json['item'][$i]['guid'] = $guid;  
$i++;