duanshan2988 2017-07-19 17:44
浏览 115
已采纳

在PHP中为JSON返回创建对象表

I'm using this script in order to make 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);


?>

In the foreach loop, it takes all the item of the feed one by one and put them in item php table.

When I return, there is no table, all item properties are sent flat:

{
    "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>
<br>
RSS feed uses include:<br>
<i><font color=\"#FF0000\">Daily Specials <br>
Entertainment <br>
Calendar 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>
<br>
RSS feed uses include:<br>
<i><font color=\"#0000FF\">Homework Assignments <br>
School Cancellations <br>
Calendar of Events <br>
Sports Scores <br>
Clubs/Organization Meetings <br>
Lunches 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>
<br>
Uses include:<br>
<i><font color=\"#0000FF\">Cyber Security Alerts <br>
Specials<br>
Job 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>
</b></i><br>
RSS uses Include:<br>
<i><font color=\"#00FF00\">Legislative Calendar<br>
Votes<br>
Bulletins</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>
<br>
Uses Include:<br>
<i><font color=\"#FF0000\">Blogs<br>
Speaking Engagements <br>
Statements<br>
 </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>
<br>
Uses Include:<br>
<i><font color=\"#0000FF\">Weather Alerts<br>
Plotting Storms<br>
School 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>
</font><br>
Feeds can be used for:<br>
<i><font color=\"#FF0000\">Open House Dates<br>
New Properties For Sale<br>
Mortgage 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>
<br>
Uses include:<br>
<i><font color=\"#0000FF\">Mortgage Rates<br>
Foreign Exchange Rates <br>
Bank Rates<br>
Specials</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>
<br>
Uses include:<br>
<i><font color=\"#0000FF\">Amber Alerts<br>
Sex Offender Community Notification <br>
Weather Alerts <br>
Scheduling <br>
Security Alerts <br>
Police Report <br>
Meetings</i></font>"
        },
        {
            "pubdate": "Tue, 19 Oct 2004 11:08:56 -0400"
        },
        {
            "guid": null
        }
    ]
}

So What is the mistake? I was thinking that the fact to put tables in item should work but apparently not :-/ How Can I make them looks more like items in this one?

{
    "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": "
<b>FeedForAll </b>helps Restaurant's communicate with customers. Let your customers know the latest specials or events.<br><br>
RSS feed uses include:<br><i>Daily Specials <br>
Entertainment <br>
Calendar of Events </i>
",
            "content": "
<b>FeedForAll </b>helps Restaurant's communicate with customers. Let your customers know the latest specials or events.<br><br>
RSS feed uses include:<br><i>Daily Specials <br>
Entertainment <br>
Calendar of Events </i>
",
            "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>
RSS feed uses include:<br><i>Homework Assignments <br>
School Cancellations <br>
Calendar of Events <br>
Sports Scores <br>
Clubs/Organization Meetings <br>
Lunches Menus </i>
",
            "content": "FeedForAll helps Educational Institutions communicate with students about school wide activities, events, and schedules.<br><br>
RSS feed uses include:<br><i>Homework Assignments <br>
School Cancellations <br>
Calendar of Events <br>
Sports Scores <br>
Clubs/Organization Meetings <br>
Lunches Menus </i>
",
            "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>
Uses include:<br><i>Cyber Security Alerts <br>
Specials<br>
Job Postings </i>
",
            "content": "FeedForAll helps Computer Service Companies communicate with clients about cyber security and related issues. <br><br>
Uses include:<br><i>Cyber Security Alerts <br>
Specials<br>
Job Postings </i>
",
            "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>
RSS uses Include:<br><i>Legislative Calendar<br>
Votes<br>
Bulletins</i>
",
            "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>
RSS uses Include:<br><i>Legislative Calendar<br>
Votes<br>
Bulletins</i>
",
            "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>
Uses Include:<br><i>Blogs<br>
Speaking Engagements <br>
Statements<br></i>
",
            "content": "FeedForAll helps Politicians communicate with the general public about positions on various issues, and keep the community notified of their schedule. <br><br>
Uses Include:<br><i>Blogs<br>
Speaking Engagements <br>
Statements<br></i>
",
            "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>
Uses Include:<br><i>Weather Alerts<br>
Plotting Storms<br>
School Cancellations </i>
",
            "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>
Uses Include:<br><i>Weather Alerts<br>
Plotting Storms<br>
School Cancellations </i>
",
            "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>
Feeds can be used for:<br><i>Open House Dates<br>
New Properties For Sale<br>
Mortgage Rates</i>
",
            "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>
Feeds can be used for:<br><i>Open House Dates<br>
New Properties For Sale<br>
Mortgage Rates</i>
",
            "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>
Uses include:<br><i>Mortgage Rates<br>
Foreign Exchange Rates <br>
Bank Rates<br>
Specials</i>
",
            "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>
Uses include:<br><i>Mortgage Rates<br>
Foreign Exchange Rates <br>
Bank Rates<br>
Specials</i>
",
            "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": "
<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>
Uses include:<br><i>Amber Alerts<br>
Sex Offender Community Notification <br>
Weather Alerts <br>
Scheduling <br>
Security Alerts <br>
Police Report <br>
Meetings</i>
",
            "content": "
<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>
Uses include:<br><i>Amber Alerts<br>
Sex Offender Community Notification <br>
Weather Alerts <br>
Scheduling <br>
Security Alerts <br>
Police Report <br>
Meetings</i>
",
            "enclosure": [],
            "categories": [
                "Computers/Software/Internet/Site Management/Content Management"
            ]
        }
    ]
}
  • 写回答

2条回答 默认 最新

  • dqrdlqpo775594 2017-07-19 17:49
    关注

    You are incrementing the counter for every property. As it is set to 0 to start with, you should only do that at the end:

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

    should be:

    $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++;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 NeRF的代码复现以及人工智能入门
  • ¥15 centos如何做一个可以让ikuai连接的openvpn
  • ¥15 Protege 中的Entities下面的界面删除了如何复原
  • ¥15 scrapy爬虫求帮
  • ¥15 imageEnView绘图问题
  • ¥15 关于#python#的问题:您好可以加您一下联系方式吗,在复现的时候确实有点问题难以解决
  • ¥15 联想电脑重装系统时无法发现硬盘
  • ¥15 MATLAB与UR10e实体机械臂建立通讯
  • ¥15 c++题需要快一点不用opencv
  • ¥15 关于#java#的问题:想要咨询Flowable流程引擎框架的问题