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

我有这个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文件的一小部分

#1楼 票数:0

基本上,答案是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; ?> ];

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

#2楼 票数:0

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

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

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

  ask by Xereoth translate from so

未解决问题?本站智能推荐:

2回复

如何使用Chart.js读取和绘制JSON

我有一个这样的html文件: ...和这样的json文件: ...,并且json加载始终失败。 我尝试了几种方法来读取json并使用Chart.js绘制图表,但始终失败。 我试图用php绘制json失败: 这怎么了
1回复

将json_encode传递到chart.js将不起作用

我正在尝试使用chart.js(最新版本)创建饼图。 我做了一个数组,我想将其作为图表的数据变量输出。 那是PHP代码: 这是我的编码值脚本: 根据文档 ,这是创建图表的方式: 这是数据变量的输入类型: 这就是我得到的: 我相信数组格式是正确的,只是键周围有引号,并且
1回复

从Ajax请求中使用Json_encoded数组重绘Chart.js图表

我有一个使用chart.js库绘制的图表。 第一次绘制非常顺利,但是我尝试使用ajax调用中的NEW数据重绘甜甜圈图。 我正在使用PHP和Codeigniter捕获我需要的所有数据,并返回json_encoded数组以重绘该图。 但是,如果我从控制台复制返回的代码并将其粘贴到它中,它就不
1回复

同一页面上带有JSON数据的chart.js未显示

我在使用 chart.js 渲染图表时遇到了一个小问题,从 MySQL 数据库中提取数据。 当我使用外部文件来提取数据时,它可以工作,但是我试图在一个文件上编写整个代码,但这给我带来了一些麻烦我假设json_encode数据没有正确提供代码如下所列:
2回复

使用数组索引0更新chart.js不起作用

我有一组图表数据对象。 我通过传递数组的索引并从对象中提取数据来更新图表数据。 这适用于除0之外的所有索引。 初始化图表时,我加载了0索引,图表也能正常工作,所以我知道这不是该特定索引的数据结构问题。 在使用0索引调用图表上的更新函数时,我没有收到任何错误。 这是一个代码笔,显示它不适用于索引 0。
1回复

条形图未在Chart.js中正确分组

我试图使用chartjs创建一个多条形图,但是没有根据每个companyName显示jobType和jobCount。 这是桌子 这是php文件( CompanySeletion.php ): 这是JS文件( testingbutton.js ): 这是HTML文件: 这是
1回复

难以使用javascript中接收的phpjson_encode数据来使用chart.js库显示图形

我正在尝试使用chart.js javascript库显示图形。 我使用PHP代码从数据库中获取数据并将其发送到javascript,方法是使用json_encode()方法从PHP获取js var。 数据实际上是表“湿度”和“温度”的两个字段。 在js中接收到数据之后,当我尝试从接收到的
1回复

如何将值传递给图表(chart.js/morris.js)

使用PHP我试图从MySQ数据库获取数据并将其显示在区域图表(收入)上。 以下是我的PHP代码: 输出是: 我已将数组传递给图表,如下所示: 但它给出了一个错误“Uncaught TypeError:无法读取属性'匹配'未定义”仅供参考我使用了以下链接 请帮我解决我的问题。