用PHP的DOM操作xml的例子
2012-1-30 17:36 Monday  

分类: PHP 评论(39) 浏览(77199)

生成:

<?php
define('IN_ECS', true);

require('../includes/init.php');

$id = isset($_GET['id'])?$_GET['id']:'';
$key = isset($_GET['key'])?$_GET['key']:'';
if($key != 'DFDAe' || empty($id))die("错误");
$sql = "select goods_id,goods_sn,goods_name,goods_img,goods_thumb from girls_goods where brand_id=$id";
$rows = $db->getAll($sql);
//print_r($rows);
$doc = new DOMDocument();
$doc->formatOutput = true;
$goods = $doc->createElement('goods');
$doc->appendChild($goods);
foreach ($rows as $row){
$good = $doc->createElement('good');

$goods_id = $doc->createElement('goods_id');
   $goods_id2 = $doc->createTextNode($row['goods_id']);
   $goods_id->appendChild($goods_id2);
$good->appendChild($goods_id);
  
$goods_sn = $doc->createElement('goods_sn');
   $goods_sn2 = $doc->createTextNode($row['goods_sn']);
   $goods_sn->appendChild($goods_sn2);
$good->appendChild($goods_sn);
  
$goods_name = $doc->createElement('goods_name');
   $goods_name2 = $doc->createTextNode($row['goods_name']);
   $goods_name->appendChild($goods_name2);
$good->appendChild($goods_name);
  
$goods_img = $doc->createElement('goods_img');
   $goods_img2 = $doc->createTextNode('http://www.togirl.cn/'.$row['goods_img']);
   $goods_img->appendChild($goods_img2);
$good->appendChild($goods_img);
  
$goods_thumb = $doc->createElement('goods_thumb');
   $goods_thumb2 = $doc->createTextNode('http://www.togirl.cn/'.$row['goods_thumb']);
   $goods_thumb->appendChild($goods_thumb2);
$good->appendChild($goods_thumb);
  

$goods->appendChild($good);
}

echo $doc->saveXML();

读取到一个数组中

<?php
//header('charset:utf-8');
$doc = new DOMDocument();

$doc->load('http://www.yiwuku.com/xml/brand.php?id=13&key=DFDAe');
$goods = $doc->getElementsByTagName('good');
$newgoods = array();
foreach ($goods as $key=>$good){
$id = $good->getElementsByTagName('goods_id');
$newgoods[$key]['goods_id'] = $id->item(0)->nodeValue;

$sn = $good->getElementsByTagName('goods_sn');
$newgoods[$key]['goods_sn'] = $sn->item(0)->nodeValue;

$name = $good->getElementsByTagName('goods_name');
$newgoods[$key]['goods_name'] = iconv('utf-8','gbk',$name->item(0)->nodeValue);

$img = $good->getElementsByTagName('goods_img');
$newgoods[$key]['goods_img'] = $img->item(0)->nodeValue;

$thumb = $good->getElementsByTagName('goods_thumb');
$newgoods[$key]['goods_thumb'] = $thumb->item(0)->nodeValue;
}

print_r($newgoods);

+1 21

留下你的看法: