我有一个创建DOMDocument XML文件的PHP函数,我需要将DOMDocument放到Javascript中,我已经考虑过使用
PHP中的函数返回DOMDocument,这是PHP函数
function coursexml($cc, $type){
$xmlfile = new DOMDocument();
if (@$xmlfile->load("books.xml") === false || $cc == "" || $type == "") {
header('location:/assignment/errors/500');
exit;
}
$string = "";
$xpath = new DOMXPath($xmlfile);
$nodes = $xpath->query("/bookcollection/items/item[courses/course='$cc']");
$x = 0;
foreach( $nodes as $n ) {
$id[$x] = $n->getAttribute("id");
$titles = $n->getElementsByTagName( "title" );
$title[$x] = $titles->item(0)->nodeValue;
$title[$x] = str_replace(" /", "", $title[$x]);
$title[$x] = str_replace(".", "", $title[$x]);
$isbns = $n->getElementsByTagName( "isbn" );
$isbn[$x] = $isbns->item(0)->nodeValue;
$bcs = $n->getElementsByTagName( "borrowedcount" );
$borrowedcount[$x] = $bcs->item(0)->nodeValue;
if ($string != "") $string = $string . ", ";
$string = $string . $x . "=>" . $borrowedcount[$x];
$x++;
}
if ($x == 0) header('location:/assignment/errors/501');
$my_array = eval("return array({$string});");
asort($my_array);
$coursexml = new DOMDocument('1.0', 'utf-8');
$coursexml->formatOutput = true;
$node = $coursexml->createElement('result');
$coursexml->appendChild($node);
$root = $coursexml->getElementsByTagName("result");
foreach ($root as $r) {
$node = $coursexml->createElement('course', "$cc");
$r->appendChild($node);
$node = $coursexml->createElement('books');
$r->appendChild($node);
$books = $coursexml->getElementsByTagName("books");
foreach ($books as $b) {
foreach ($my_array as $counter => $bc) {
$bnode = $coursexml->createElement('book');
$bnode = $b->appendChild($bnode);
$bnode->setAttribute('id', "$id[$counter]");
$bnode->setAttribute('title', "$title[$counter]");
$bnode->setAttribute('isbn', "$isbn[$counter]");
$bnode->setAttribute('borrowedcount', "$borrowedcount[$counter]");
}
}
}
return $coursexml;
}
所以我想做的是在Javascript中调用该函数,并返回DOMDocument。
答案 0 :(得分:1)
尝试以下
<?php include('coursexml.php'); ?>
<script>
var xml = <?php $xml = coursexml("CC140", "xmlfile");
echo json_encode($xml->saveXML()); ?>;
document.write("output" + xml);
var xmlDoc = (new DOMParser()).parseFromString(xml, 'text/xml');
</script>
答案 1 :(得分:0)
你可以简单地把这个函数放到一个URL上(例如把它放在一个独立的文件中?这取决于你),然后通过AJAX从客户端调用它。有关拨打此类电话的详细信息,请参阅How to make an AJAX call without jQuery?。
修改强> 尝试创建一个简单的PHP文件,其中包含并调用您拥有的函数。从你到目前为止所描述的内容来看,它可能看起来像
<?php
include("functions.php");
print coursexml($cc, $type);
假设此文件名为xml.php,当您通过http://mydomain.com/xml.php中的浏览器访问它时,您应该看到XML文档(到目前为止与Javascript无关)。
现在,在主文档中,您将包含一个Javascript,它将调用此URL来加载XML。一个例子是(假设你正在使用jQuery,对于一个简单的Javascript函数引用上面的链接):
$.ajax({
url: "xml.php",
success: function(data){
// Data will contain you XML and can be used in Javascript here
}
});