繁体   English   中英

使用chart.js将转换后的rss读取为json文件不起作用

Reading converted rss to json file with chart.js not working

提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供   中文繁体   英文版本   中英对照 版本,有任何建议请联系yoyou2525@163.com。

我正在尝试解决一些我认为应该可以解决的问题^ _ ^

我有这个PHP代码:

<?php

class XmlToJson {

    public static function Parse ($url) {

        $fileContents= file_get_contents($url);

        $fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);

        $fileContents = trim(str_replace('"', "'", $fileContents));

        $simpleXml = simplexml_load_string($fileContents);

        $json = json_encode($simpleXml);

        return $json;

    }

}

?>

在这里,我读出了Xml(RSS feed)并用它制作了一个Json。

在我的showfeed.php中,我有以下代码:

<?php

include 'encode.php';

$json = XmlToJson::Parse("http://rss.cnn.com/rss/edition.rss");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script src="Chart.js"></script>
</head>
<body>
<div id="json">
<?php
echo $json;
?>
</div>
                <div id="chartCanvas">
                    <canvas id="canvas" height="600" width="600"></canvas>
                    <canvas id="canvas2" height="600" width="600"></canvas>
                    <br>
                </div>
<script type="text/javascript">
var myData = [document.getElementById("json")];
var myData2 = [document.getElementById("json")];


                    Array.prototype.mapProperty = function(property) {
                                        return this.map(function (obj) {
                                            return obj[property];
                                        });

                                    };

            // Example: myData.mapProperty('rank') to get an array of all ranks 
                    lineChartData = {
                    labels: myData.mapProperty('title'),
                     datasets : [
                       {
                            label: "My First dataset",
                            fillColor : "rgba(220,220,220,0.2)",
                            strokeColor : "rgba(220,220,220,1)",
                            pointColor : "rgba(220,220,220,1)",
                            pointStrokeColor : "#fff",
                            pointHighlightFill : "#fff",
                            pointHighlightStroke : "rgba(220,220,220,1)",
                            data : myData.mapProperty(12)
                        }
                                ]
               };
                    lineChartData2 = {
                    labels : myData2.mapProperty('v'),
                     datasets : [
                       {
                            label: "My First dataset",
                            fillColor : "rgba(220,220,220,0.2)",
                            strokeColor : "rgba(220,220,220,1)",
                            pointColor : "rgba(220,220,220,1)",
                            pointStrokeColor : "#fff",
                            pointHighlightFill : "#fff",
                            pointHighlightStroke : "rgba(220,220,220,1)",
                            data : myData2.mapProperty('eid')
                        }
                                ]
               };


                window.onload = function()
                {
                    var ctx = document.getElementById("canvas").getContext("2d");
                    window.myLine = new Chart(ctx).Line(lineChartData);
                    var ctx2 = document.getElementById("canvas2").getContext("2d");
                    window.myLine2 = new Chart(ctx2).Line(lineChartData2);
                }
</script>
</body>
</html>

我没有隐藏Echo $ json,所以我可以查看它是否仍然有效,否则我将div置于隐藏状态。

但是我要解决的是,回显$json ,然后我希望var myData en myData2具有Json的值。 从这里开始,我尝试在Json之外创建一个数组,以便可以使用它绘制图表。 如果可以用,我想我可以使用例如标题作为图表中的标签,并使用Json中的数字作为数据。

但是我要么使它变得太困难而可能有一种更简单的方法,要么我在代码或思想中犯了一个错误。

因此,我想做的是:阅读RSS feed并使用特定信息创建Chart.js。 我认为将RSS转换为Json时最简单,但这可能就是我。 但是,使用此代码,我得到的只是一个空图表,那么如何读取我制作的Json变量并实际使用RSS中的标题作为标签?

希望这里有人可以提供帮助。 (图表的插件为Chart.js)

编辑我的$ jsone回声是这样的:

{"@attributes":{"version":"2.0"},"channel":{"title":"CNN.com - Top Stories","link":"http:\/\/edition.cnn.com\/index.html?eref=edition","description":"CNN.com delivers up-to-the-minute news and information on the latest top stories, weather, entertainment, politics and more.","language":"en-US","copyright":"Copyright 2015 Cable News Network LP, LLLP.","pubDate":"Wed, 14 Jan 2015 14:03:23 EST","ttl":"10","image":{"title":"CNN.com - Top Stories","link":"http:\/\/edition.cnn.com\/index.html?eref=edition","url":"http:\/\/i.cdn.turner.com\/cnn\/.e\/img\/1.0\/logo\/cnn.logo.rss.gif","width":"144","height":"33","description":"CNN.com delivers up-to-the-minute news and information on the latest top stories, weather, entertainment, politics and more."},"item":[{"title":"Al Qaeda affiliate claims Charlie Hebdo killings","guid":"http:\/\/edition.cnn.com\/2015\/01\/14\/europe\/charlie-hebdo-france-attacks\/index.html","link":"http:\/\/edition.cnn.com\/2015\/01\/14\/europe\/charlie-hebdo-france-attacks\/index.html?eref=edition","description":"Al Qaeda in the Arabian Peninsula claims responsibility for the attack at France's Charlie Hebdo satirical newspaper in which 12 people died. More than 50 legal cases are opened against people in France for allegedly expressing support for terrorism since the massacre.","pubDate":"Wed, 14 Jan 2015 11:17:32 EST"},{"title":"What is al Qaeda in the Arabian Peninsula?","guid":"http:\/\/edition.cnn.com\/2015\/01\/14\/middleeast\/yemen-al-qaeda-arabian-peninsula\/index.html","link":"http:\/\/edition.cnn.com\/2015\/01\/14\/middleeast\/yemen-al-qaeda-arabian-peninsula\/index.html?eref=edition","description":"A leader of al Qaeda in the Arabian Peninsula says it carried out the Hebdo massacre. What do we know about the Islamist group?","pubDate":"Wed, 14 Jan 2015 11:22:26 EST"},{"title":"Al Qaeda desperate not to be eclipsed by ISIS?","guid":"http:\/\/edition.cnn.com\/2015\/01\/14\/europe\/al-qaeda-attack-claim-analysis\/index.html","link":"http:\/\/edition.cnn.com\/2015\/01\/14\/europe\/al-qaeda-attack-claim-analysis\/index.html?eref=edition","description":"AQAP's claims of responsibility for the Charlie Hebdo attack is remarkably complex and hints at the messy rivalry perhaps engulfing the jihadi world, writes CNN's Nick Paton Walsh.","pubDate":"Wed, 14 Jan 2015 12:28:45 EST"},{"title":"Mixed response to new Mohammed cover","guid":"http:\/\/edition.cnn.com\/2015\/01\/13\/living\/muslims-respond-hebdo\/index.html","link":"http:\/\/edition.cnn.com\/2015\/01\/13\/living\/muslims-respond-hebdo\/index.html?eref=edition","description":"The image of Mohammed on the new cover of Charlie Hebdo has elicited a mixed reaction from Muslims, from wariness and appreciation to annoyance and anger.","pubDate":"Wed, 14 Jan 2015 02:11:51 EST"},{"title":"How orphan brothers took wrong turn","guid":"http:\/\/edition.cnn.com\/2015\/01\/13\/world\/kouachi-brothers-radicalization\/index.html","link":"http:\/\/edition.cnn.com\/2015\/01\/13\/world\/kouachi-brothers-radicalization\/index.html?eref=edition","description":"They were the perfect targets for recruiters of jihad: two young French brothers from an immigrant family, virtually alone in the French capital.","pubDate":"Wed, 14 Jan 2015 00:23:55 EST"},{"title":"Tangled trail reveals new suspects","guid":"http:\/\/edition.cnn.com\/2015\/01\/13\/europe\/france-charlie-hebdo-attack-trail\/index.html","link":"http:\/\/edition.cnn.com\/2015\/01\/13\/europe\/france-charlie-hebdo-attack-trail\/index.html?eref=edition","description":"Investigators follow leads taking then from a Paris newsroom to Yemen and Bulgaria as they try to work out how the attacks were planned -- and who is still at large.","pubDate":"Wed, 14 Jan 2015 13:56:20 EST"},{"title":"Astronauts scramble after alarm","guid":"http:\/\/edition.cnn.com\/2015\/01\/14\/us\/international-space-station-emergency\/index.html","link":"http:\/\/edition.cnn.com\/2015\/01\/14\/us\/international-space-station-emergency\/index.html?eref=edition","description":"A possible leak in the cooling system on the International Space Station has resulted in the evacuation of the U.S. crew from the American segment of the station to the Russian segment, NASA said Wednesday. ","pubDate":"Wed, 14 Jan 2015 10:10:45 EST"},{"title":"Turkey bans Hebdo cover online","guid":"http:\/\/edition.cnn.com\/2015\/01\/14\/world\/turkey-charlie-hebdo\/index.html","link":"http:\/\/edition.cnn.com\/2015\/01\/14\/world\/turkey-charlie-hebdo\/index.html?eref=edition","description":"A Turkish court has banned Web pages that show the new cover of Charlie Hebdo, the country''s semiofficial news agency Anadolu reported Wednesday.","pubDate":"Wed, 14 Jan 2015 10:57:27 EST"},{"title":" AirAsia plane's fuselage found","guid":"http:\/\/edition.cnn.com\/2015\/01\/14\/world\/airasia-disaster\/index.html","link":"http:\/\/edition.cnn.com\/2015\/01\/14\/world\/airasia-disaster\/index.html?eref=edition","description":"Searchers have located the fuselage of AirAsia Flight QZ8501 in the Java Sea, the head of Indonesia's search and rescue agency said Wednesday, raising the prospect that many bodies of the 162 aboard the flight that crashed last month will soon be found.","pubDate":"Wed, 14 Jan 2015 13:53:49 EST"},{"title":"Police rescue 37 babies ","guid":"http:\/\/edition.cnn.com\/2015\/01\/14\/china\/china-child-trafficking-bust\/index.html","link":"http:\/\/edition.cnn.com\/2015\/01\/14\/china\/china-child-trafficking-bust\/index.html?eref=edition","description":"Police rescued 37 babies and a 3-year-old girl after busting a child trafficking ring in eastern China's Shandong province, reported the state-run China Central Television.","pubDate":"Wed, 14 Jan 2015 11:02:46 EST"},{"title":"U.S. airports tighten security","guid":"http:\/\/edition.cnn.com\/2015\/01\/14\/us\/airport-security-aqap\/index.html","link":"http:\/\/edition.cnn.com\/2015\/01\/14\/us\/airport-security-aqap\/index.html?eref=edition","description":"The Department of Homeland Security is increasing security checks at American airports because of concerns over new bomb-making instructions released by al Qaeda in Yemen (AQAP), the terrorist group which U.S. intelligence agencies believe may have been behind the Charlie Hebdo attack in Paris, U.S. officials tell CNN.","pubDate":"Wed, 14 Jan 2015 07:53:40 EST"},{"title":"Former Spanish King faces paternity suit","guid":"http:\/\/edition.cnn.com\/2015\/01\/14\/europe\/spain-former-king-paternity-suit\/index.html","link":"http:\/\/edition.cnn.com\/2015\/01\/14\/europe\/spain-former-king-paternity-suit\/index.html?eref=edition","description":"Spain's former King Juan Carlos, 77, will face a paternity lawsuit -- by a Belgian woman alleging that he's her father -- before the nation's Supreme Court, a 12-judge panel ruled Wednesday. ","pubDate":"Wed, 14 Jan 2015 14:02:01 EST"},{"title":"Home alone children die in fire","guid":"http:\/\/edition.cnn.com\/2015\/01\/14\/us\/louisiana-children-house-fire\/index.html","link":"http:\/\/edition.cnn.com\/2015\/01\/14\/us\/louisiana-children-house-fire\/index.html?eref=edition","description":"Two children, left alone in their Louisiana home, were killed in a house fire while their mother was out getting her hair styled at a salon, authorities said. ","pubDate":"Wed, 14 Jan 2015 08:39:19 EST"},{"title":"Gay woman denied funeral request","guid":"http:\/\/edition.cnn.com\/2015\/01\/14\/us\/colorado-gay-woman-funeral-service\/index.html","link":"http:\/\/edition.cnn.com\/2015\/01\/14\/us\/colorado-gay-woman-funeral-service\/index.html?eref=edition","description":"Family and friends of a gay woman in Colorado have expressed anger at a church's refusal to show a video at her funeral that contained images of the woman kissing her partner. ","pubDate":"Wed, 14 Jan 2015 03:09:58 EST"},{"title":"Man survives fall from cruise ship","guid":"http:\/\/edition.cnn.com\/2015\/01\/13\/us\/man-overboard-cruise-rescue\/index.html","link":"http:\/\/edition.cnn.com\/2015\/01\/13\/us\/man-overboard-cruise-rescue\/index.html?eref=edition","description":"A man who fell from a Royal Caribbean cruise ship off the coast of Cozumel, Mexico, was rescued by a Disney cruise ship after passengers spotted him on the water, Mexican authorities say. ","pubDate":"Tue, 13 Jan 2015 21:27:25 EST"},{"title":"Judge: No delay in Tsarnaev trial","guid":"http:\/\/edition.cnn.com\/2015\/01\/14\/justice\/tsarnaev-trial-no-delay\/index.html","link":"http:\/\/edition.cnn.com\/2015\/01\/14\/justice\/tsarnaev-trial-no-delay\/index.html?eref=edition","description":"A federal judge on Wednesday denied a request to push back the trial of alleged Boston Marathon bomber Dzhokhar Tsarnaev, who'd requested a delay after last week's terrorist attacks in France.","pubDate":"Wed, 14 Jan 2015 10:07:51 EST"}

这只是巨大的Json / XML文件的一小部分

2 个回复

基本上,答案是document.getElementById("json")仅给您一个HTML元素。 如果需要该元素的内容,请使用document.getElementById("json").innerHTML

但是, innerHTML的内容将是字符串,而不是Json对象。 如果您希望myData的内容是Json对象,而不是仅格式化为看起来像Json的文本,则需要在其上使用JSON.parse() ,或者做更多类似的事情:

var myData = <?php echo $json; ?>;

要么

var myData = [ <?php echo $json; ?> ];

不确定数组部分是做什么的,但也许您需要它。

看起来您要将DOM元素拉入数组中?

您是否尝试过:data = JSON.parse(document.getElementById(“ json”)。innerHTML)

这应该先提取JSON字符串,然后对它进行正确的字符串解析(而不是对象),然后解析它。

1 Json到Chart.js不起作用

我们从Internet上获得了此文件,并且可以通过某种方式在console中将输出获取为JSON ,但是chartdisplay.js并未采用JSON文件。 你能帮助我吗。 谢谢! 的HTML content.php chartdisplay.js 这就是 ...

2 在Chart.js中使用JSON文件数据

javascript新手。 我试图读取位于我的本地主机( http:// localhost:8080 / jsonData.json )上的JSON文件,并将其格式化为使用Chart.js显示。 这是我的JSON文件: 和我的HTML文件将显示图表: 基本上,当我运行它 ...

3 打开 json 文件以在 chart.js 中创建图表

我正在尝试根据 json 文件中的数据创建图表。 我是编码新手,不确定我在这里做错了什么。 数据未显示在控制台日志中,我收到错误消息:Uncaught TypeError:无法读取图:71 处未定义的属性“日期” 这是我的旧 javascript 代码 我的 json 文件中的数据如下所示 ...

4 来自 C# 的 JSON 结果不适用于 Chart.js

我试图在 c# 中返回一个 json 对象,然后将它传递给我的 javscript 控制器。 我正在点击 c# 控制器,然后返回到 js 控制器,但在使用我的 json 对象格式化 chart.js 图表时遇到问题。 我需要使用 json.stringify 或 json.parse 吗? 我的 ...

5 通过AJAX JSON向Chart.js提供数据无法正常工作?

我正在构建一个仪表板,我想将数据库中的信息直接显示到Chart.js。 我创建了Ajax,它返回了正确的数据。 我将其全部放在以下代码中: 但是,在加载页面时,该图不会出现。 Firebug也不是错误,仅此警告与Chart.js文件有关: canvas:尝试将stro ...

6 如何在Chart.JS中使用PHP制作JSON

大家。 我想要的是带有来自PHP数据的Bubble Chart(Chart.js)。 PHP执行python文件。 *实际上,执行复杂的算法,但是这里用test.py简化了。 的index.php test.py 的index.php 我必须像这样将结果从ph ...

7 在 Chart.js 中显示 JSON

我正在从本地文件中获取和解析 JSON 数据,并且我正在使用Chart.js来显示数据。 我想要显示的数据是给定单词的使用次数以及作为图表标签的单词。 问题: 我已经设法在wordCount函数中获得了单词和出现对。 如果我注销counts ,我可以看到比赛。 我的痛点是如何正确显示我目前拥有的 ...

8 将json加载到chart.js中

我想通过ajax将jsonData加载到chart.js对象中。 我的问题是将jsondata作为字符串引用到chart.js 我认为ajax()。responseText检索一个字符串,但chart.js数据需要一个数组? 我正在使用谷歌图表,它运作良好。 这是我的代码 ...

9 JSON欠缺的Chart.JS

大家好,我遇到了问题,我无法显示我的图表,它会变成这样 如你所见,我也打印控制台日志,没有任何错误发生。 以下是我的index.php 我的chartmain.js 我的Json阵列 我认为也许它无法从JSON读取我的数据,但在控制台日志中却显示为 ...

10 PHP到JSON到chart.js

我一直在尝试将该脚本传递给JSON的PHP循环(我想我已经弄清楚了。然后使用JSON结果通过chart.js生成折线图。 我尝试传递到图表的JSON脚本。 &lt;?php echo $_SESSION['amort_JSON']; ?&gt; 上面回显的 ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2022 STACKOOM.COM