Skip to content

Instantly share code, notes, and snippets.

@alexzhou
Created June 23, 2014 07:45
Show Gist options
  • Save alexzhou/4112a97cdc4134dc7399 to your computer and use it in GitHub Desktop.
Save alexzhou/4112a97cdc4134dc7399 to your computer and use it in GitHub Desktop.
基于XML的ajax 数据交换
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function loadDoc(url) {
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", url, false);
xmlhttp.send();
return xmlhttp.responseXML;
}
function displayResult()
{
var xmlDoc = loadDoc("http://localhost/test.php");
$(xmlDoc).find('item').each(function(index,item){
var title = $(item).find('title');
var tr = '<tr><td>'+ $(item).find('title').text()+'</td><td>'+ $(item).find('content').text()+'</td><td>'+ $(item).find('pubdate').text()+'</td>';
$("#content table tbody").append(tr);
})
}
</script>
</head>
<body onload="displayResult()">
<div id='content'>
<table border=1>
<thead>
<tr>
<th>标题</th>
<th>内容</th>
<th>出版日期</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
</html>
<?PHP
header("Content-Type:text/xml");
$data_array = array(
array(
'title' => 'title1',
'content' => 'content1',
'pubdate' => '2009-10-11',
),
array(
'title' => 'title2',
'content' => 'content2',
'pubdate' => '2009-11-11',
)
);
// 属性数组
$attribute_array = array(
'title' => array(
'size' => 1
)
);
$string = <<<XML
<?xml version='1.0' encoding='utf-8'?>
<article>
</article>
XML;
$xml = simplexml_load_string($string);
foreach ($data_array as $data) {
$item = $xml->addChild('item');
if (is_array($data)) {
foreach ($data as $key => $row) {
$node = $item->addChild($key, $row);
if (isset($attribute_array[$key]) && is_array($attribute_array[$key]))
{
foreach ($attribute_array[$key] as $akey => $aval) {
// 设置属性值
$node->addAttribute($akey, $aval);
}
}
}
}
}
echo $xml->asXML();
@alexzhou
Copy link
Author

json用久了 xml 生疏了,复习一下

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment