lets say I have a folder named "fruits" and inside that folder I have three folders named "apple", "grape", and "banana" and inside each of those I have a jpg of the fruit (apple.jpg, etc). In this situation the folder "fruits" is stored on a server: jackfruits.com/weirdfood/fruits/
how would I go about creating an XML that has a format
<fruits>
<fruit>apple</fruit>
<fruit>grape</fruit>
<fruit>banana</fruit>
</fruits>
and grabbing each of the jpgs then requesting that info in javascript and putting it in an html? like if I wanted to put them in an html so that the resulting page would look something like:
banana
PICTURE OF BANANA
<?php
$url = "jackfruits.com/weirdfood/fruits/";
outputXml($url);
function outputXml($url) {
$files = glob($url . "*");
$dom = new DOMDocument();
$fruits = $dom->createElement("fruits");
$dom->appendChild($fruits);
foreach($files as $file) {
#need to create new element "fruit" and put file name in text within it
#then append to fruits
}
header("Content-type: text/xml");
print($dom->saveXML());
}
(function() {
"use strict";
window.onload = function() {
getRequest;
};
function ajax(address, ffunction) {
var request = new XMLHttpRequest();
request.onload = ffunction;
request.open("GET", address, true);
request.send();
}
function getRequest(value) {
ajax("fruits.php?", displayXml);
}
function displayXml() {
var xml = this.responseXML;
document.getElementById("allfruit").innerHTML = xml.querySelector("fruits").textContent;
}
})();
Note that getRequest;
isn't calling the function. It should be getRequest();
.
You could simplify the directory scan with scandir()
.
function outputXml($url) {
$files = scandir($url);
$dom = new DOMDocument();
$fruits = $dom->createElement("fruits");
$dom->appendChild($fruits);
foreach($files as $file) {
if($file!='.'&&$file!='..'&&is_dir($file)) {
$fruit=$dom->createElement("fruit");
$fruit->nodeValue=$file;
$fruits->appendChild($fruit);
}
}
header("Content-type: text/xml");
print($dom->saveXML());
}
Not tested. Of course assuming that you are sure of your directory structure: jackfruits.com/weirdfood/fruits/ x / x .jpg. You will have to change the code a little bit if there are other files or you'll have to use recursion to walk the subdirectories if there are more levels.
Then, when you do
document.getElementById("allfruit").innerHTML=xml.querySelector("fruits").textContent
You're showing the xml code inside the #allfuit
div... You'll have to parse it and generate the html!
...Or simply return the html from php:
function outputXml($url) {
$files = scandir($url);
foreach($files as $file) {
if($file!='.'&&$file!='..'&&is_dir($file)) {
echo '<div>'.$fruit.'<br><img src="weirdfood/fruits/'.$fruit.'/'.$fruit.'.jpg"></div>';
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.