XML:eXtensible Markup Language,可扩展的标签语言,本身是一种字符串格式,用于描述批量复合数据,
语法特点:
(1)所有的数据放在标签中
(2)整个XML字符串有且只能有一个根标签
(3)所有的标签名都可以自定义,但严格区分大小写,且开始和结束标记必须完全一样
(4)每个标签都可以自定义属性,属性必须有值,值必须用单引号/双引号括起来
(5)每个标签都可以定义任意的子标签,标签可以嵌套,但不能交叉
注意:HTML和XML的区别
HTML语法随意;XML语法严格;
HTML标签预定义好了;XML标签都是自定义的;
HTML用于描述网页的结构;XML标签用于描述数据;
下面是一段我们需要用来携带数据信息的XML,接下来我们要通过PHP构建XML格式的数据
<?xml version="1.0" encoding="UTF-8" ?> <productlist> <product pid="101"> <pname>三星</pname> <price>35.50</price> <pic>1.jpg</pic> </product> <product pid="102"> <pname>闪迪</pname> <price>45.50</price> <pic>2.jpg</pic> </product> <product pid="103"> <pname>金士顿</pname> <price>30.50</price> <pic>3.jpg</pic> </product> </productlist>
PHP构建XML结构数据并响应
<?php header(‘Content-Type:application/xml‘); $conn = mysqli_connect("127.0.0.1","root","","dangdang",3306); $sql = "SET NAMES UTF8"; mysqli_query($conn,$sql); $sql = "SELECT * FROM book"; $result = mysqli_query($conn,$sql); $list = mysqli_fetch_all($result,MYSQLI_ASSOC); $str = "<?xml version=‘1.0‘ encoding=‘UTF-8‘ ?>"; $str .= "<productlist>"; foreach($list as $b){ $str .= "<product pid=‘$b[bid]‘><pname>$b[bname]</pname><price>$b[price]</price><pic>$b[pic]</pic></product>"; } $str .= "</productlist>"; echo $str;
接收XML并解析 因为XML属于XMLDOM对象 只能使用核心DOM方法进行解析
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>...</title> <style> #btLoadMore{ display:block; width:100%; margin: 20px auto; padding:5px; } </style> </head> <body> <table width="100%" border="1"> <thead> <tr> <th>编号</th> <th>名称</th> <th>价格</th> <th>图片</th> </tr> </thead> <tbody id="tbodyList"> <tr> <td colspan="4"></td> </tr> </tbody> </table> <button id="btLoadMore">加载更多</button> <script type="text/javascript"> btLoadMore.onclick = function(){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState===4){ if(xhr.status==200){ doResponse(xhr); }else{ alert("响应完成但有问题"); } } } xhr.open("GET","book_select.php",true); xhr.send(null); function doResponse(xhr){ var list= xhr.responseXML.querySelectorAll("product"); //console.log(list); var frag = ""; for(var i = 0 ; i<list.length ; i++){ var b = list[i]; var id = b.getAttribute("bid"); var bn = b.querySelector("pname").innerHTML; var pr = b.querySelector("price").innerHTML; var pc = b.querySelector("pic").innerHTML; console.log(pc); frag+=`<tr> <td>${bn}</td> <td>${pr}</td> <td>${pc}</td> <tr>`; } tbodyList.innerHTML=frag; } } </script> </body> </html>
时间: 2024-12-28 09:03:49