Я пытаюсь исправить то, что, на мой взгляд, должно работать ^ _ ^
У меня есть этот код 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-канал) и делаю из него 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-канал и использовать конкретную информацию для создания 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
Похоже, вы помещаете элемент DOM в массив?
Вы пробовали: data = JSON.parse (document.getElementById («json»). InnerHTML)
Это должно получить строку JSON, а затем проанализировать ее, если она была правильно структурирована (а не объект, иначе вы получите ошибку).
В основном ответ таков: 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; ?> ];
Не уверен, для чего предназначена часть массива, но, возможно, вам это нужно.