加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

pear中几个实用的xml代码库

发布时间:2020-12-16 09:20:40 所属栏目:百科 来源:网络整理
导读:1.XML_Beautifier 用于将一段排版凌乱的XML文档美化 ?phprequire_once "XML/Beautifier.php";$fmt = new XML_Beautifier();$result = $fmt-formatFile('originalFile.xml','beautifiedFile.xml');if (PEAR::isError($result)) { echo $result-getMessage();

1.XML_Beautifier

用于将一段排版凌乱的XML文档美化

<?php
require_once "XML/Beautifier.php";
$fmt = new XML_Beautifier();
$result = $fmt->formatFile('originalFile.xml','beautifiedFile.xml');

if (PEAR::isError($result)) {
    echo $result->getMessage();
    exit();
}
echo "File beautified,awaiting orders!<br />";
?>

2.XML_DTD

引用外部的dtd文件以对xml内容进行验证

<?php

require_once 'XML/DTD/XmlValidator.php';

$dtd_file = realpath('myfile.dtd');
$xml_file = realpath('myfile.xml');

$validator = new XML_DTD_XmlValidator();
if (!$validator->isValid($dtd_file,$xml_file)) {
    die($validator->getMessage());
}

?>


3.XML_Feed_Parser

解析各种主流格式的Feed(xml,atom,rss1,rss2等格式)

<?php
/* The file you wish to parse */
$source = 'my_source.xml';

/* Where Relax NG is available,we can force validation of the feed */
$validate = true;

/* Whether or not to suppress non-fatal warnings */
$suppress_warnings = false;

/* If the feed is not valid XML and the tidy extension is installed we can
 * attempt to use it to fix the feed */
$use_tidy = true;

$feed = new XML_Feed_Parser($source,$validate,$suppress_warnings,$use_tidy);

foreach ($feed as $entry) {
    print $entry->title . "n";
}

$first_entry = $feed->getEntryByOffset(0);

$particular_entry = $feed->getEntryById('http://jystewart.net/entry/1');
?>


4.XML_Parser

SAX模型的 XML 解析器,相对于DOM解析器在解析时需要将这个xml树加载到内存中,SAX在某些应用中表现的更加轻量级。

<?php
require_once 'XML/Parser.php';

class myParser extends XML_Parser
{
  function myParser()
  {
    parent::XML_Parser();
  }

 /**
  * 处理起始标签
  *
  * @access private
  * @param  resource  xml parser 句柄
  * @param  string    标签名
  * @param  array     属性值
  */
  function startHandler($xp,$name,$attribs)
  {
    printf('handle start tag: %s<br />',$name);
  }

 /**
  * 处理结束标签
  *
  * @access private
  * @param  resource  xml parser 句柄
  * @param  string    标签名
  */
  function endHandler($xp,$name)
  {
    printf('handle end tag: %s<br />',$name);
  }

 /**
  * 处理字符数据
  *
  * @access private
  * @param  resource  xml parser 句柄
  * @param  string    字符数据
  */
  function cdataHandler($xp,$cdata)
  {
    // does nothing here,but might e.g. print $cdata
  }
}

$p = &new myParser();

$result = $p->setInputFile('xml_parser_file.xml');
$result = $p->parse();
?>

5.XML_Query2XML

实用query语句直接从数据库中调取数据并转换成XML(支持PDO,PEAR MDB2,PEAR DB,ADOdb)

<?php
  require_once 'XML/Query2XML.php';
  $pdo = new PDO('mysql://root@localhost/Query2XML_Tests');
  $query2xml = XML_Query2XML::factory($pdo);
  $artistid = $_REQUEST['artistid'];
  $dom = $query2xml->getXML(
    array(
      'data' => array(
        ":$artistid"
      ),'query' => 'SELECT * FROM artist WHERE artistid = ?'
    ),array(
      'rootTag' => 'favorite_artist','idColumn' => 'artistid','rowTag' => 'artist','elements' => array(
        'name','birth_year','music_genre' => 'genre'
      )
    )
  );
  header('Content-Type: application/xml');
  $dom->formatOutput = true;
  print $dom->saveXML();
?>


6.XML_RDDL

读取资源目录描述语言(Resource Directory Description Language,RDDL)
<?php
require_once "XML/RDDL.php";

// create new RDDL parser
$rddl   = &new XML_RDDL();

// parse a document that contains RDDL resources
$result = $rddl->parseRDDL('http://www.rddl.org');
// check for error
if (PEAR::isError($result)) {
  echo    sprintf( "ERROR: %s (code %d)",$result->getMessage(),$result->getCode());
  exit;
}

// get all resources
$resources = $rddl->getAllResources();
echo    "<pre>";
print_r($resources);
echo    "</pre>";

//    get one resource by its Id
$test = $rddl->getResourceById('CSS');
echo    "<pre>";
print_r($test);
echo    "</pre>";

// get all stylesheets
$test = $rddl->getResourcesByNature('http://www.w3.org/1999/XSL/Transform');
echo    "<pre>";
print_r($test);
echo    "</pre>";

// get all normative references
$test = $rddl->getResourcesByPurpose('http://www.rddl.org/purposes#normative-reference');
echo    "<pre>";
print_r($test);
echo    "</pre>";
?>

7.XML_RSS

RSS解析器
<?php
require_once "XML/RSS.php";

$rss =& new XML_RSS("http://rss.slashdot.org/Slashdot/slashdot");
$rss->parse();

echo "<h1>Headlines from <a href="http://slashdot.org">Slashdot</a></h1>n";
echo "<ul>n";

foreach ($rss->getItems() as $item) {
    echo "<li><a href="" . $item['link'] . "">" . $item['title'] . "</a></li>n";
}

echo "</ul>n";
?>

8.XML_Serializer

XML生成器
<?php
require_once 'XML/Serializer.php';

$options = array(
    "indent"    => "    ","linebreak" => "n","typeHints" => false,"addDecl"   => true,"encoding"  => "UTF-8","rootName"   => "rdf:RDF","defaultTagName" => "item"
);

$stories[] = array(
    'title'       => 'First Article','link'        => 'http://freedomink.org/node/view/55','description' => 'Short blurb about article........'
);

$stories[] = array(
    'title'       => 'Second Article','link'        => 'http://freedomink.org/node/view/11','description' => 'This article shows you how ......'
);

$data['channel'] = array(
    "title" => "Freedom Ink","link"  => "http://freedomink.org/",$stories
);

$serializer = new XML_Serializer($options);

if ($serializer->serialize($data)) {
    header('Content-type: text/xml');
    echo $serializer->getSerializedData();
}
?>


9.XML_sql2xml

通过sql语句直接从数据库中调取数据转化成xml
<?php
  require_once "XML/sql2xml.php";
  $sql2xmlclass = new xml_sql2xml("mysql://username:password@localhost/xmltest");
  $xmlstring = $sql2xmlclass->getxml("select * from bands");
?>

10.XML_Statistics

XML数据统计,标签个数,结构深度等,相当好用
<?php
require_once "XML/Statistics.php";
$stat = new XML_Statistics(array("ignoreWhitespace" => true));
$result = $stat->analyzeFile("example.xml");

if ($stat->isError($result)) {
    die("Error: " . $result->getMessage());
}

// total amount of tags:
echo "Total tags: " . $stat->countTag() . "<br />";

// count amount of 'title' attribute,in all tags
echo "Occurences of attribute title: " . $stat->countAttribute("title") . "<br />";

// count amount of 'title' attribute,only in <section> tags
echo "Occurences of attribute title in tag section: " . $stat->countAttribute("title","section") . "<br />";

// count total number of tags in depth 4
echo "Amount of Tags in depth 4: " . $stat->countTagsInDepth(4) . "<br />";

echo "Occurences of PHP Blocks: " . $stat->countPI("PHP") . "<br />";

echo "Occurences of external entity 'bar': " . $stat->countExternalEntity("bar") . "<br />";

echo "Data chunks: " . $stat->countDataChunks() . "<br />";

echo "Length of all data chunks: " . $stat->getCDataLength() . "<br />";

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读