pear中几个实用的xml代码库

前端之家收集整理的这篇文章主要介绍了pear中几个实用的xml代码库前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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 />";
原文链接:https://www.f2er.com/xml/297373.html

猜你在找的XML相关文章