首页 > 编程技术 > php

简单入门级php 生成xml文档代码

发布时间:2016-11-25 16:55

$doc = new domdocument('1.0');
// we want a nice output
$doc->formatoutput = true;

 代码如下 复制代码

$root = $doc->createelement('book');
$root = $doc->appendchild($root);

$title = $doc->createelement('title');$title = $root->appendchild($title);

$text = $doc->createtextnode('this is the title');
$text = $title->appendchild($text);

echo "retrieving all the document: ";
echo $doc->savexml() . " ";

echo "retrieving only the title part: ";
echo $doc->savexml($title);

<?
if (defined('_class_rss_php教程')) return;
define('_class_rss_php教程',1);
/**
 
 *  使用说明:
 *  $rss = new rss('redfox','http://111cn.net/',"redfox's blog");
 *  $rss->additem('rss class',"http://www.111cn.net","xxx",date());
 *  $rss->additem(...);
 *  $rss->savetofile(...);
 */

 

 代码如下 复制代码

class rss {
   //public
   $rss_ver = "2.0";
   $channel_title = '';
   $channel_link = '';
   $channel_description = '';
   $language = 'zh_cn';
   $copyright = '';
   $webmaster = '';
   $pubdate = '';
   $lastbuilddate = '';
   $generator = 'redfox rss generator';


   $content = '';
   $items = array();


   function rss($title, $link, $description) {
       $this->channel_title = $title;
       $this->channel_link = $link;
       $this->channel_description = $description;
       $this->pubdate = date('y-m-d h:i:s',time());
       $this->lastbuilddate = date('y-m-d h:i:s',time());
   }


   function additem($title, $link, $description ,$pubdate) {
       $this->items[] = array('titile' => $title ,
                        'link' => $link,
                        'description' => $description,
                        'pubdate' => $pubdate);
   }


   function buildrss() {
       $s = "<!--l version="1.0" encoding="gb2312"--> ";
       // start channel
       $s .= " ";
       $s .= " "
       $s .= "<link />{$this->channel_link} ";
       $s .= "{$this->channel_description} ";
       $s .= "{$this->language} ";
       if (!empty($this->copyright)) {
          $s .= "{$this->copyright} ";
       }
       if (!empty($this->webmaster)) {
          $s .= "{$this->webmaster} ";
       }
       if (!empty($this->pubdate)) {
          $s .= "{$this->pubdate} ";
       }


       if (!empty($this->lastbuilddate)) {
          $s .= "{$this->lastbuilddate} ";
       }


       if (!empty($this->generator)) {
          $s .= "{$this->generator} ";
       }
     
       // start items
       for ($i=0;$iitems),$i++) {
           $s .= " ";
           $s .= " ";
           $s .= "<link />{$this->items[$i]['link']} ";
           $s .= "<!--data[{$thi-->items[$i]['description']}]]> ";
           $s .= "{$this->items[$i]['pubdate']} ";         
           $s .= " ";
       }
    
      // close channel
      $s .= " ";
      $this->content = $s;
   }


   function show() {
       if (empty($this->content)) $this->buildrss();
       header('content-type:text/xml');
       echo($this->content);
   }


   function savetofile($fname) {
       if (empty($this->content)) $this->buildrss();
       $handle = fopen($fname, 'wb');
       if ($handle === false)  return false;
       fwrite($handle, $this->content);
       fclose($handle);
   }
}


?>
同时也可以用网页特效来解析xml文档

//解析xml实例一
$objDOM = new DOMDocument();
$objDOM->load("xml.xml");
$parent = $objDOM->getElementsByTagName("Product");
foreach( $parent as $value )
  {
    $names = $value->getElementsByTagName("Name");
    $name  = $names->item(0)->nodeValue;
   
    $urls = $value->getElementsByTagName("Url");
    $url  = $urls->item(0)->nodeValue;
   
    $images = $value->getElementsByTagName("Image");
    $image  = $images->item(1)->nodeValue;
  }
 
 //DOMDocument实例二
 
$xml = new DOMDocument();
$xml->load("me.xml");
$postDom = $xml->getElementsByTagName("post");
foreach($postDom as $post){
$title = $post->getElementsByTagName("title");
echo "Id: " . $title->item(0)->attributes->item(0)->nodeValue . "<br />";
echo "Title: " . $title->item(0)->nodeValue . "<br />";
echo "Details: " . $post->getElementsByTagName("details")->item(0)->nodeValue . "<br /><br />";
}
 
?>
xml.xml
<Root>
        <Category>
                <Product>
                        <Name>网页制作教程教程</Name>
                        <Image>
                                <SizeName>Small</SizeName>
                                <Url>http://www.111cn.net</Url>
                        </Image>
                        <Image>
                                <SizeName>Medium</SizeName>
                                <Url>http://www.111cn.net</Url>
                        </Image>
                        <Image>
                                <SizeName>Large</SizeName>
                                <Url>http://www.111cn.net</Url>
                        </Image>
                </Product>
        </Category>
</Root>


me.xm;

<?xml version="1.0" encoding="utf-8"?>
<phplamp>
<post>
<title id="1">PHP XML处理介绍一</title>
<details>详细内容一</details>
</post>
<post>
<title id="2">PHP XML处理介绍二</title>
<details>详细内容二</details>
</post>
<post>
<title id="3">PHP XML处理介绍三</title>
<details>详细内容三</details>
</post>
</phplamp>

在php中解析xml文档用专门的函数domdocument来处理,把json在php中也有相关的处理函数,我们要把数据xml 数据存到一个数据再用json_encode直接换成json数据就OK了。

/*
<?xml version='1.0' encoding='utf-8' ?>
<root cityid="0" classid="0" placeid="0" yy="0" mm="0" pg="1" ps教程="20" maxPage="1" num="1" serverIP="58.57.65.195">
<expo ID="3889" cityid="53" city="北京" classid="0" classname="建筑/装潢/五金" place="中国国际展览中心" placeid="0" tm1="2010-6-3" tm2="2010-6-5" title="20会" Address="北
里河路13号">
<![CDATA[2010北京第十五届中件系列]]>
</expo>
</root>

*/

<?php
$url = "http://www.111cn.net/xml.xml";

$dom = new DOMDocument();
$dom->load($url);
$root = $dom->documentElement;
$arr=array();
foreach ($root->childNodes as $item)
{
        if($item->hasChildNodes())
        {
                $tmp=array();
                foreach($item->childNodes as $one)
                {
                        $tmp[$one->tagName]=$one->nodeValue;
                }
               
                $arr[$item->tagName]=$tmp;
        }
}

$jsonStr = json_encode($arr);

var_dump($jsonStr);

/*

*/
?>

 代码如下 复制代码

//xml string
$xml_string="<?xml version='1.0'?>
<users>
<user id='398'>
<name>Foo</name>
<email>foo@bar.com</name>
</user>
<user id='867'>
<name>Foobar</name>
<email>foobar@foo.com</name>
</user>
</users>";

//load the xml string using simplexml
$xml = simplexml_load_string($xml_string);

//loop through the each node of user
foreach ($xml->user as $user)
{
//access attribute
echo $user['id'], ' ';
//subnodes are accessed by -> operator
echo $user->name, ' ';
echo $user->email, '<br />';
}

json数据解析代码

 

 代码如下 复制代码

$json_string='{"id":1,"name":"foo","email":"foo@foobar.com","interest":["wordpress","php"]} ';
$obj=json_decode($json_string);
echo $obj->name; //prints foo
echo $obj->interest[1]; //prints php


//xml string
$xml_string="<?xml version='1.0'?>
<users>
<user id='398'>
<name>Foo</name>
<email>foo@bar.com</name>
</user>
<user id='867'>
<name>Foobar</name>
<email>foobar@foo.com</name>
</user>
</users>";

//load the xml string using simplexml
$xml = simplexml_load_string($xml_string);

//loop through the each node of user
foreach ($xml->user as $user)
{
//access attribute
echo $user['id'], ' ';
//subnodes are accessed by -> operator
echo $user->name, ' ';
echo $user->email, '<br />';
}

php还自带了一个PHP XML Parser
PHP XML Parser 简介
XML 函数允许我们解析 XML 文档,但无法对其进行验证。

XML 是一种用于标准结构化文档交换的数据格式。您可以在我们的 XML 教程 中找到更多有关 XML 的信息。

该扩展使用 Expat XML 解析器。

Expat 是一种基于事件的解析器,它把 XML 文档视为一系列事件。当某个事件发生时,它调用一个指定的函数处理它。

Expat 是无验证的解析器,忽略任何链接到文档的 DTD。但是,如果文档的形式不好,则会以一个错误消息结束。

由于它基于事件,且无验证,Expat 具有快速并适合 web 应用程序的特性。

XML 解析器函数允许我们创建 XML 解析器,并为 XML 事件定义句柄。

标签:[!--infotagslink--]

您可能感兴趣的文章: