PHP操作XML,学习三,PHP生产XML代码案例

作者: JONE 分类: PHP/MySQL 发布时间: 2017-09-02 00:07

demo-1 推荐

<?php

$conn = mysql_connect('127.0.0.1','root','root');
mysql_set_charset('utf8',$conn);
mysql_select_db('blog');
$sql = 'select * from bl_article LEFT JOIN bl_category ON c_id = bl_category.id';
$result = mysql_query($sql);

header("Content-type:text/xml");
$xmlStr = '<?xml version="1.0" encoding="UTF-8" ?>';

$xmlStr .= '<atricle>';
while ($rs = mysql_fetch_assoc($result)) {
 $xmlStr .= '<list>';
 $xmlStr .= '<id>'.$rs['id'].'</id>';
 $xmlStr .= '<title>'.$rs['a_name'].'</title>';
 $xmlStr .= '<className>'.$rs['c_name'].'</className>';
 $xmlStr .= '<content><![CDATA['.$rs['a_content'].']]></content>';
 $xmlStr .= '<dateTime>'.date('Y-m-d H:i:s', $rs['a_publishtime']).'</dateTime>';
 $xmlStr .= '</list>';
}
$xmlStr .= '</atricle>';
echo $xmlStr;

demo-2

<?php

//header('Content-type:text/html; charset=utf-8');
$id = 10;//$_GET['id'];

$conn = mysql_connect('127.0.0.1','root','root');
mysql_select_db('blog',$conn);
mysql_set_charset('utf8');

$sql = "SELECT * FROM bl_article WHERE id = {$id}";
$resource = mysql_query($sql);

$rs = mysql_fetch_assoc($resource);

//echo '<pre>';
//var_dump($rs);

header("Content-type:text/xml");
$dom = new DOMDocument('1.0', 'utf-8');
$dom->formatOutput = true;
// 创建节点(跟节点)
$newsShow = $dom->createElement("newsShow");
$dom->appendChild($newsShow);
// 创建属性
$newsId = $dom->createAttribute("id");
$newsShow->appendChild($newsId);
// 属性添加值
$newsIdText = $dom->createTextNode($rs['id']);
$newsId->appendChild($newsIdText);
// 创建节点
$title = $dom->createElement("title");
$newsShow->appendChild($title);
// 节点添加内容
$titleText = $dom->createTextNode($rs['a_name']);
$title->appendChild($titleText);
// 创建节点
$content = $dom->createElement("content");
$newsShow->appendChild($content);
// 节点添加CDATA内容
$contentText = $dom->createCDATASection($rs['a_content']);
$content->appendChild($contentText);
// 保存并输出
echo $dom->saveXML();
2条评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注