`
haohappy2
  • 浏览: 326347 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

how to generate XML using PHP

阅读更多

用PHP生成XML文件的常见方法如下:

【XML文件内容】
 <?xml version="1.0" encoding="utf-8"?>
<article>
    <item>
        <title size="1">title1</title>
        <content>content1</content>
        <pubdate>2009-10-11</pubdate>
    </item>
    <item>
        <title size="1">title2</title>
        <content>content2</content>
        <pubdate>2009-11-11</pubdate>
    </item>
</article>

【直接生成字符串】
方法1:使用纯粹的PHP代码生成字符串,并把这个字符串写入一个以XML为后缀的文件。这是最原始的生成XML的方法,不过有效!
PHP代码如下:
 <?PHP
$data_array = array(
    array(
    'title' => 'title1',
    'content' => 'content1',
        'pubdate' => '2009-10-11',
    ),
    array(
    'title' => 'title2',
    'content' => 'content2',
    'pubdate' => '2009-11-11',
    )
);
$title_size = 1;
 
$xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
$xml .= "<article>\n";
 
foreach ($data_array as $data) {
    $xml .= create_item($data['title'], $title_size, $data['content'], $data['pubdate']);
}
 
$xml .= "</article>\n";
 
echo $xml;
 
//  创建XML单项
function create_item($title_data, $title_size, $content_data, $pubdate_data) {
    $item = "<item>\n";
    $item .= "<title size=\"" . $title_size . "\">" . $title_data . "</title>\n";
    $item .= "<content>" . $content_data . "</content>\n";
    $item .= " <pubdate>" . $pubdate_data . "</pubdate>\n";
    $item .= "</item>\n";
 
    return $item;
}
 
 
?>

【DomDocument】
方法2:使用DomDocument生成XML文件
创建节点使用createElement方法,
创建文本内容使用createTextNode方法,
添加子节点使用appendChild方法,
创建属性使用createAttribute方法
PHP代码如下:
 <?PHP
$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
    )
);
 
//  创建一个XML文档并设置XML版本和编码。。
$dom=new DomDocument('1.0', 'utf-8');
 
//  创建根节点
$article = $dom->createElement('article');
$dom->appendchild($article);
 
foreach ($data_array as $data) {
    $item = $dom->createElement('item');
    $article->appendchild($item);
 
    create_item($dom, $item, $data, $attribute_array);
}
 
echo $dom->saveXML();
 
function create_item($dom, $item, $data, $attribute) {
    if (is_array($data)) {
        foreach ($data as $key => $val) {
            //  创建元素
            $$key = $dom->createElement($key);
            $item->appendchild($$key);
 
            //  创建元素值
            $text = $dom->createTextNode($val);
            $$key->appendchild($text);
 
            if (isset($attribute[$key])) {  //  如果此字段存在相关属性需要设置
                foreach ($attribute[$key] as $akey => $row) {
                    //  创建属性节点
                    $$akey = $dom->createAttribute($akey);
                    $$key->appendchild($$akey);
 
                    // 创建属性值节点
                    $aval = $dom->createTextNode($row);
                    $$akey->appendChild($aval);
                }
            }   //  end if
        }
    }   //  end if
}   //  end function
?>

【XMLWriter】
方法3:使用XMLWriter类创建XML文件
此方法在PHP 5.1.2后有效
另外,它可以输出多种编码的XML,但是输入只能是utf-8
PHP代码如下:
 <?PHP
$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
    )
);
 
$xml = new XMLWriter();
$xml->openUri("php://output");  //  输出方式,也可以设置为某个xml文件地址,直接输出成文件
$xml->setIndentString('  ');
$xml->setIndent(true);
 
$xml->startDocument('1.0', 'utf-8');    //  开始创建文件
//  根结点
$xml->startElement('article');
 
foreach ($data_array as $data) {   
    $xml->startElement('item');
 
    if (is_array($data)) {
        foreach ($data as $key => $row) {
            $xml->startElement($key);
 
            if (isset($attribute_array[$key]) && is_array($attribute_array[$key])) {
                foreach ($attribute_array[$key] as $akey => $aval) {    //  设置属性值
                    $xml->writeAttribute($akey, $aval);
                }
 
            }
 
            $xml->text($row);   //  设置内容
            $xml->endElement(); // $key
        }
 
    }
    $xml->endElement(); //  item
}
 
$xml->endElement(); //  article
$xml->endDocument();
 
$xml->flush();
?>

【SimpleXML】
方法4:使用SimpleXML创建XML文档

 <?PHP
$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();
 

分享到:
评论

相关推荐

    RJS Templates for Rails

    Unlike conventional Rails templates that generate HTML or XML, RJS templates generate JavaScript code that is executed when it is returned to the browser. This JavaScript generation allows you to ...

    PROFESSIONAL F# 2.0

    This chapter teaches how to parse and generate XML using the built-in XML support in F#. - **ASP.NET MVC (Chapter 21):** ASP.NET MVC is a popular web framework. This chapter provides an introduction ...

    Odoo 11 Development Essentials 3 Edition(epub)

    Chapter 5, Import, Export, and Module Data, covers the most used Odoo data file formats—XML and CSV—the external identifier concept, how use to data file in modules, and data import/export ...

    GWT in Action

    This chapter explains how to leverage JSON to communicate with external APIs, including an example of using JSON to interact with the Yahoo Search API. #### Chapter 14: Automating Code Generation ...

    Flask Web Development.pdf 最新 原版

    - **Scale Applications Using Packages and Modules:** Advanced developers can explore how to structure larger applications using packages and modules to ensure scalability and maintainability. ...

    Java邮件开发Fundamentals of the JavaMail API

    Instructions on how to download and install the JavaMail API are contained in the course. In addition, you will need a development environment such as the JDK 1.1.6+ or the Java 2 Platform, Standard...

    VB编程资源大全(英文源码 其它)

    &lt;END&gt;&lt;br&gt;85,Shape.zip I have used SHAPE command instead of PARAMETERS to generate dynamic report.Open with VB6. &lt;END&gt;&lt;br&gt;86,AlarmPrj.zip An Alarm Class project. &lt;END&gt;&lt;br&gt;87,hyperlink.zip A ...

    vs 2005 10款插件

    Using XML comments, you can mark up your code and then, using a tool like nDoc, you can generate help files or MSDN-like Web documentation based on those comments. The only problem with XML ...

    VB编程资源大全(英文源码 数据库)

    1 , datafile.zip "This sample demonstrates how to do file input and output using Visual Basic. The sample creates a new database file and allows you to view, add, or delete records in this database...

    JavaScript权威指南(第五版).chm

    The broad and deep coverage of client-side JavaScript is illustrated with many sophisticated examples that demonstrate how to: Generate a table of contents for an HTML document Display DHTML ...

    Lerner -- Python Workout. 50 Essential Exercises -- 2020.pdf

    - **Objective:** Generate XML documents. - **Key Concepts:** - Understanding XML structure and syntax. - Using the `xml.etree.ElementTree` module for creating XML documents. 26. **Prefix Notation...

    javascript.the.definitive.guide.5th.2006(英文版)

    The broad and deep coverage of client-side JavaScript is illustrated with many sophisticated examples that demonstrate how to: Generate a table of contents for an HTML document Display DHTML ...

    Java_for_the_Web_with_Servlets

    - **JSP Directives**: Directives provide instructions to the JSP engine about how to compile the page. Common directives include `page`, `include`, and `taglib`. - **JSP Actions**: JSP actions are ...

    Parasoft Handbook

    Creating a new project from a WSDL file ensures that your WSDL conforms to the schema and passes XML validation tests. Here are the steps to create a new project: 1. **Step 1**: Go to File → Click ...

    apktool documentation

    original = META-INF folder / AndroidManifest.xml, which are needed to retain the signature of apks to prevent needing to resign. Used with -c / --copy-original on [b]uild unknown = Files / folders ...

Global site tag (gtag.js) - Google Analytics