I have an external JavaScript file, I would like to display array content in my PHP page. How can I display the content by loop. I tried to display the content using following code. But Failed.
<?php
ini_set('allow_url_fopen', 'On');
$feed = file_get_contents("https://example.com/media-list.js");
$array = json_decode($json);
var_dump($array);
$urlPoster=array();
foreach ($array as $value) {
$urlPoster[]=$value->urlPoster;
}
print_r($urlPoster);
?>
media-list.js content
var contents = {
"0W7EHsR8":{
"attachmentCode":"0W7EHsR8",
"title":"title1",
},
"vciym7Zb4":{
"attachmentCode":"vciym7Zb4",
"title":"title2",
},
"XlKBM6":{
"attachmentCode":"XlKBM6",
"title":"Title3",
}
};
I would like to display content like
Title is "title1" .
Title is "title2".
You are trying to use json_decode() on a Javascript Array. JSON and Javascript are two different things.
You need to convert your contents array to JSON, save it in a different file (contents.json for example) and load that file with file_get_contents.
If you need to do this only once you can do something like
var contents = {
"0W7EHsR8":{
"attachmentCode":"0W7EHsR8",
"title":"title1",
},
"vciym7Zb4":{
"attachmentCode":"vciym7Zb4",
"title":"title2",
},
"XlKBM6":{
"attachmentCode":"XlKBM6",
"title":"Title3",
}
};
console.log(JSON.stringify(contents));
and copy the result from the console (click CTRL+Shift+I to open it).
JSON.stringify() takes a Javascript array and turns it into a JSON string.
for this small array the JSON equivalent is
{"0W7EHsR8":{"attachmentCode":"0W7EHsR8","title":"title1"},"vciym7Zb4":{"attachmentCode":"vciym7Zb4","title":"title2"},"XlKBM6":{"attachmentCode":"XlKBM6","title":"Title3"}}
If you intend on making this dynamic (say, loading all attachemnts from a database) you can create a php file that loads that data into an array and returns it into proper JSON using json_encode(). Loading that file with file_get_contents and using json_decode like you are doing now should do the trick.
Related
I have a php file where I retrieved data from the server. I want to parse the data into my pure Javascript file in order to store it in an array.
This is my php code:
$dir = "images";
$folders = array_diff(scandir($dir), array('..', '.'));
$folders = array_values($folders);
print_r($folders);
$encodedArray = json_encode($folders);
print_r($encodedArray);
I want to send over the encodedArray to my pure Javascript file as I want to put them into an array to use. Is it possible to send it to a pure JS file?
you can print your variable JSON "echo $encodedArray", and you can use fetch to get data from your url. ex: fetch("https://getdatafromserver.php");
I'm trying to move an array into a .json file and then simply console.log it. I think its my structure in my array that is messing it up.
$jsonarray = array('Symbol'=>[$symbol],'PERatio'=>[$peratio], 'MarketCap'=>[$marketcap], 'Dividend'=>[$dividend], 'ROE'=>[$roe], 'DebtToEbitda'=>[$debttoebitda], 'EbitdaGrowth' =>[$ebitdagrowth], 'RevenueGrowth' =>[$revenuegrowth],);
file_put_contents('Stockdata1.json', json_encode($jsonarray), FILE_APPEND);
This is how it looks like in the .json file.
{"Symbol":["A"],"PERatio":["31.55"],"MarketCap":["19722.500"],"Dividend":["0.87"],"ROE":["14.48"],"DebtToEbitda":["2.04"],"EbitdaGrowth":["5.40"],"RevenueGrowth":["4.20"]}{"Symbol":["AA"],"PERatio":["44.45"],"MarketCap":["6960.660"],"Dividend":["0.00"],"ROE":["2.33"],"DebtToEbitda":["0.95"],"EbitdaGrowth":["0.00"],"RevenueGrowth":["0.00"]}{"Symbol":["AAC"],"PERatio":["0.00"],"MarketCap":["217.730"],"Dividend":["0.00"],"ROE":["-2.76"],"DebtToEbitda":["8.71"],"EbitdaGrowth":["22.30"],"RevenueGrowth":["15.00"]}{"Symbol":["AAP"],"PERatio":["18.68"],"MarketCap":["6888.440"],"Dividend":["0.26"],"ROE":["12.69"],"DebtToEbitda":["1.17"],"EbitdaGrowth":["6.50"],"RevenueGrowth":["13.60"]}
when i then try to console.log in js like this
$.getJSON('Stockdata1.json', function (data) {
console.log(data);
});
nothing comes out... Hope someone can see my mistake..
As soon as you FILE_APPEND the second array, you're invalidating the JSON in the file. The file will contain two JSON objects without a separator (i.e. (abbreviated for clarity) {"Symbol":["A"]}{"Symbol":["B"]}).
Instead, what you need for valid JSON, is to have the file contain a JSON array of all objects: [{"Symbol":["A"]},{"Symbol":["B"]}]. The only way to do that, is to not use file_put_contents() with the FILE_APPEND flag, but to load the file as JSON, add the new object, and write the full JSON back to the file.
My suggestion is to change your code to something along these lines:
$jsonarray = array('Symbol'=>[$symbol],'PERatio'=>[$peratio], 'MarketCap'=>[$marketcap], 'Dividend'=>[$dividend], 'ROE'=>[$roe], 'DebtToEbitda'=>[$debttoebitda], 'EbitdaGrowth' =>[$ebitdagrowth], 'RevenueGrowth' =>[$revenuegrowth],);
$data = json_decode(file_get_contents('Stockdata1.json'));
if (!$data) {
// file is empty or does not contain valid JSON
$data = [];
} elseif (is_object($data)) {
// file only contains a JSON object, not a JSON array
$data = [ $data ];
}
$data[] = $jsonarray;
file_put_contents('Stockdata1.json', json_encode($data));
I'd like to merge multiple pages from a game into a single page. For example:
http://politicsandwar.com/api/tradeprice/resource=aluminum
http://politicsandwar.com/api/tradeprice/resource=food
I tried Javascript using $.ajax() and $.getJSON(). I got a "No 'Access-Control-Allow-Origin" error. So I can't use these tools.
I can actually access those sites as plaintext and parse it as JSON later.
But I can't seem to find any way to parse multiple websites into a single file. It seems to be a trivial thing, considering there are so many tools that can scrape complex content within websites. I just need something that can combine it as plaintext!
I'm open to using any language for this.
You can use PHP to load those files.
Use an array to parse the URL's using file_get_contents and concatenate it to a string and the parse.
$urls = array("http://politicsandwar.com/api/tradeprice/resource=aluminum","http://politicsandwar.com/api/tradeprice/resource=food");
$json = array();
for ($i=0; $i < count($urls); $i++) {
// Push the decoded JSON from the URL
array_push($json, json_decode(file_get_contents($urls[$i]) ));
}
// Set the content type to JSON and echoes it
header('Content-Type: application/json');
echo json_encode($json);
I've been looking for a way to lazy load JSON data from an API (since I'm making about 5+ API calls a page)
and I found this: https://github.com/rpnzl/jquery-lazyjson/tree/v1.0
Seem like a nice class but since I'm using PHP all over my website and the call made by this class is with JavaScript, I have no idea how to combine it with my PHP code to make my website loads "by parts".
My goal is to load fast what's possible, then load dynamically each API call one by one to make website runs smoother.
I would like to hear any ideas for handling multiple API calls and fetching the data dynamically.
This is how I'm fetcing my data right now. all PHP and about 7 seconds of loading:
//Get the match!
$matches = $data->getMatchHistory($playerId,$characterId); //Returns an array of each match found
if ($matches == 0)
{
//Todo when user not in game
echo '<div class="alert alert-danger"><h2>We\'re sorry..<br/>There are no matches for this player with '.$playerId.'</div>';
} else {
for($i=0;$i<sizeof($matches)-1;$i++)
{
$match[$i] = new Match();
$match[$i]->matchId = $matches[$i]['matchId'];
$match[$i]->charName = $data->getCharacterName($matches[$i]['character']);
$match[$i]->stats = $data->getMatchStats($match[$i]->matchId); // Makes another API call and returns the match statistics. One Match = 2 API calls
}
?>
<h2><?=$playerName?> Match History</h2>
<?php
for ($i=0;$i<sizeof($matches)-1;$i++)
{
?>
<!--ALOT OF HTML,CSS, AND data fetching this way:-->
<?=matches[$i]->someData;?>
<?php
}
?>
You might as well use PHP to decode and get JSON from API calls.
$JSON = file_get_contents("API-URL.json");
If we know that the file_get_contents returns a page to a variable (in this case, a JSON string), we can then decode the received JSON using PHP.
$Array = json_decode($JSON, 1);
Let's say you've got a json string of {"playerid": 1298134, "gender": "male"}, you could access these via $Array["playerid"] and $Array["gender"], and they would return the variable.
The same goes if you have a array inside the JSON, eg {"playerid": 1298134, "gender": "male", "personal": {"fname": "Kieran", "lname": "Cross"}} could be accessed as $Array["playerid"] and $Array["personal"]["fname"]
If you wish to decode the API at the top of your page, quickly, you can easily do
$Array = json_decode(file_get_contents("API-Page.json"), 1);
You can read more on this here, on the PHP documentation.
i'm trying to update is a javascript which when you hover over an image, a div object floats near your mouse with information, this information is stored in a .js file as an array,
eg.
Text[0]=["image 1","data 1"]
Text[1]=["image 2","data 2"]
in the past if this array is change/data added to/removed from it would require uploading a new copy of the .js file, if data was added to/removed from it would also require a change to the .dwt file for the new image which would update every file that use the .dwt file as the main template which could result in 20+ pages being uploaded
i figured i can automate this by using the database by flagging records if they are active and using a mysql query to get only those which are active, this way a blackened app can add to the database and deactivate record thus eliminating having to upload files every so soften.
to do this, i had planned on storing the information in the database and building the above array based off the results, researching how to use mysql queries in javascript lead me to code like this
$.ajax( "path/to/your.php" )
.done(function() { alert("success"); })
.fail(function() { alert("error"); })
now i understand that i need to make a .php file which runs my query and that my formatting of the query results into the array would be one in the .done part but what i don't understand is what i'm supposed to do in the .php file to output the query results how in the .done part i'm supposed to reference the output
bellow is the code i use to echo my query results to the page to ensure i am getting results
$resultIndex = 0
while($row = $results->fetch_array(MYSQLI_ASSOC))
{
echo '<'.strval($resultIndex).'><br>';
echo 'id = 'strval($row['id']).'<br>';
echo 'name = 'strval($row['name']).'<br>';
echo 'desc = 'strval($row['desc']).'<br>';
echo 'active = 'strval($row['active']).'<br>';
echo '-----------------------<br>';
$resultIndex += 1;
}
i am wondering 2 things
do i just echo or print_r what i want returned from my .php file
how to i access what my .php file returns in .done
I recommend using http://www.php.net/json_encode to output into Json. Yes, just echo the output. On success, a callback is called passed with the data from server.
$.post (url, function (data){
//do some stuff with data from server
});
See http://api.jquery.com/jQuery.post/
Your $.ajax function just points to a page and reads the data on that page. If you want that page to use MySQL, you will need to use php to set up the MySQL query and print the data. The layers of a web app are complicated, but I'll try to break it down for you.
A traditional php/mysql setup works like this:
Javascript:
Client side, only deals with content already available on the page. Often edits html based on user interaction.
HTML
Client side, defines the content on a page
PHP
Server side, runs on the server and construct the html
MYSQL
Server side, used to communicate between the php and the database
Database
Server side, used to permanently store data
Ajax is a way for the Javascript layer to call some php in the background. That php can use MySQL to access data in the database and print it out in a format that the javascript can parse and use. Typically the javascript will then edit the HTML.