在PHP中创建XML文档时出错

时间:2016-10-20 12:03:16

标签: php xml simplexml

尝试从数据库数据创建XML文档时出现此错误:

  第1行第2行的

错误:文档末尾的额外内容

这是我的代码:

<?php
header('Content-type: text/xml');

$mysqli = new mysqli('127.0.0.1', 'root', '', 'db_test');

$xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><root></root>');

$currency = $xml->addChild('currency');
$currency->addAttribute('rate', '8');
$currency->addAttribute('code', 'PLZ');

$catalog = $xml->addChild('catalog');
$items = $xml->addChild('items');

$result = $mysqli->query("SELECT * FROM `catalog`");
while($it = $result->fetch_object()) {
    $item = $items->addChild('item');
    $item->addAttribute('id', $it->id);
    $item->addAttribute('selling_type', "r");
    $item->addChild('name', $it->name.", ".$it->comment);
    $item->addChild('categoryId', $it->parent_id);
    $item->addChild('priceplz', $it->cost);    

    $r = $mysqli->query("SELECT `image` FROM `catalog_images` WHERE `catalog_id`='".$it->id."' AND `main`=1 LIMIT 1");
    if($i = $r->fetch_object()){
      $item->addChild('image', "/Media/images/catalog/big/".$i->image);
    }
    unset($r);
    unset($i);

    $item->addChild('barcode', $it->artikul);
    $item->addChild('description', $it->text);
    $item->addChild('available', "true");
    unset($item);
}
unset($result);
unset($it);

$result = $mysqli->query("SELECT * FROM `catalog_tree`");
while($cat = $result->fetch_object()) {
    $category = $catalog->addChild('category', $cat->name);
    $category->addAttribute('id', $cat->id);
    if($cat->parent_id != 0) {
        $category->addAttribute('portal_id', $cat->id);
        $category->addAttribute('parentId', $cat->parent_id);
    }
    unset($category);
}
unset($result);
unset($cat);

$mysqli->close();

$xml->asXML('text.xml');

?>

如果我对这些项目发表评论&#39;循环它工作正常,否则它不起作用...... 我是盲人还是什么?

0 个答案:

没有答案