如何使用 PHP 在 GCIDE XML 中搜索 [英] How to search inside GCIDE XML using PHP

查看:23
本文介绍了如何使用 PHP 在 GCIDE XML 中搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从其网站.

该包包含各种 XML 文件.我在我的 Windows PC 上运行 PHP 和 Apache.如何使用 PHP 在这些 XML 文件中搜索单词及其定义?

你的项目引起了我的兴趣,并认为我可能会在某个时候发现它有用,所以做了一些研究,并找到了下面的 此页面上的代码.我运行了这个 php,目前我的数据库中有一个功能齐全的字典!

这是我为启动和运行它所做的一切(我将 XML 文件解压缩到包含这些文件的文件夹中名为 XML 的文件夹中).

SQL for Table - gcide

创建表`gcide`(`id` int(11) NOT NULL AUTO_INCREMENT,`word` varchar(255) 默认为空,`定义`文本,`pos` varchar(50) 默认为空,`fld` varchar(50) 默认为空,主键(`id`),关键字`词`(`词`)) 引擎=MyISAM

用于 gcide XML 导入的 PHP - import_gcide_xml.php

 (.*?)<\/hw>(.*?)(.*?)<\/def>/", $original_file, $results);$blocks = $results[0];//遍历块数组for ($j = 0; $j <= count($blocks)-1; $j++) {preg_match_all("/(.*?)<\/hw>/", $blocks[$j], $wordarray);$words = $wordarray[0];$word = addlashes(strip_tags($words[0]));$word = preg_replace('{-}', ' ', $word);$word = preg_replace("/[^a-zA-Z0-9\s]/", "", $word);preg_match_all("/(.*?)<\/def>/", $blocks[$j], $definitionarray);$definitions = $definitionarray[0];$definition = addedlashes(strip_tags($definitions[0]));$definition = preg_replace('{-}', ' ', $definition);$definition = preg_replace("/[^a-zA-Z0-9\s]/", "", $definition);preg_match_all("/(.*?)<\/pos>/", $blocks[$j], $posarray);$poss = $posarray[0];$pos = addedlashes(strip_tags($poss[0]));$pos = preg_replace('{-}', ' ', $pos);$pos = preg_replace("/[^a-zA-Z0-9\s]/", "", $pos);preg_match_all("/(.*?)<\/fld>/", $blocks[$j], $fldarray);$flds = $fldarray[0];$fld = addedlashes(strip_tags($flds[0]));$fld = preg_replace('{-}', ' ', $fld);$fld = preg_replace("/[^a-zA-Z0-9\s]/", "", $fld);$insertsql = "INSERT INTO gcide (word, definition, pos, fld) VALUES ('$word', '$definition', '$pos', '$fld')";$insertresult = mysql_query($insertsql) 或 die(mysql_error());回声 $word."".$定义."\n";}}}echo '完成!';?>

搜索页面的 CSS - gcide.css

body{ font-family:Arial, Helvetica, sans-serif;}#search_box { 填充:4px;边框:实心 1px #666666;底边距:15px;宽度:300px;高度:30px;字体大小:18px;-moz-border-radius:6px;-webkit-border-radius:6px;}#search_results { 显示:无;}.word { 字体粗细:粗体;}.found { 字体粗细:粗体;}dl { 字体系列:衬线;}DT { 字体粗细:粗体;}dd { 字体粗细:正常;}.pos { 字体粗细:正常;}.fld { margin-right:10px;}

搜索页面的 HTML - index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><头><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>PHP、GCIDE的jQuery搜索</title><link href="gcide.css" rel="stylesheet" type="text/css"/><link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/ui-lightness/jquery-ui.css" rel="stylesheet" type="text/css"/><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script><script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script><script type="text/javascript">$(函数(){$("#search_box").keyup(function() {//获取用户输入的值var searchString = $("#search_box").val();//形成查询字符串var data = 'search='+ searchString;//如果搜索字符串不为空如果(搜索字符串){//ajax调用$.ajax({类型:POST",网址:gcide_search.php",数据:数据,beforeSend: function(html) {//这发生在实际调用之前$("#results").html('');$("#search_results").show();$(".word").html(searchString);},success: function(html){//这发生在我们得到结果之后$("#results").show();$("#results").append(html);}});}返回假;});});<身体><div class="ui-widget-content" style="padding:10px;"><input id="search_box" class='search_box' type="text"/><div id="search_results"><span class="word"></span></div>的搜索结果<dl id="结果"></dl>

</html>

用于 jQuery 搜索的 PHP - gcide_search.php

query($query);$end_result = '';如果($结果){while ( $r = $result->fetch(PDO::FETCH_ASSOC) ) {$end_result .='
'.$r['word'];if($r['pos']) $end_result .= ',<span class="pos">'.$r['pos'].'</span>';$end_result .= '</dt>';$end_result .='
';if($r['fld']) $end_result .= '<span class="fld">('.$r['fld'].')</span>';$end_result .= $r['定义'];$end_result .= '</dd>';}}如果(!$end_result){$end_result = '<dt><div class="ui-state-highlight ui-corner-all" style="margin-top: 20px; padding: 0 .7em;"><p><span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>没有找到结果.

</div></dt>';}回声 $end_result;}?>

I downloaded GCIDE (GNU Project's publication of CIDE, the Collaborative International Dictionary of English) from its website.

The package contains various XML files. I am running PHP with Apache in my Windows PC. How can I search for a word and its definition in these XML files using PHP?

解决方案

Your project intrigued me, and thought I might find it useful sometime, so did some research, and found the below code on this page. I ran this php, and currently have a fully functional dictionary in my database!

Here's everything I did to get it up and running (I unzipped the XML files into a folder called XML within the folder that contains these files).

SQL for Table - gcide

CREATE TABLE `gcide` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `word` varchar(255) DEFAULT NULL,
  `definition` text,
  `pos` varchar(50) DEFAULT NULL,
  `fld` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `word` (`word`)
) ENGINE=MyISAM

PHP for gcide XML Import - import_gcide_xml.php

 <?php
    $connection = mysql_connect('localhost', 'root', '') or die('Could not connect to MySQL database. ' . mysql_error());
    $db = mysql_select_db('fiddle',$connection);

    mysql_query('TRUNCATE TABLE gcide') or die(mysql_error());

    $xml = array('xml/gcide_a.xml', 'xml/gcide_b.xml', 'xml/gcide_c.xml', 'xml/gcide_d.xml', 'xml/gcide_e.xml','xml/gcide_f.xml','xml/gcide_g.xml', 'xml/gcide_h.xml', 'xml/gcide_i.xml', 'xml/gcide_j.xml', 'xml/gcide_k.xml', 'xml/gcide_l.xml', 'xml/gcide_m.xml', 'xml/gcide_n.xml', 'xml/gcide_o.xml', 'xml/gcide_p.xml', 'xml/gcide_q.xml', 'xml/gcide_r.xml', 'xml/gcide_s.xml', 'xml/gcide_t.xml', 'xml/gcide_u.xml', 'xml/gcide_v.xml', 'xml/gcide_w.xml', 'xml/gcide_x.xml', 'xml/gcide_y.xml', 'xml/gcide_z.xml');
    $numberoffiles = count($xml);

    for ($i = 0; $i <= $numberoffiles-1; $i++) {
        $xmlfile = $xml[$i];
        // original file contents
        $original_file = @file_get_contents($xmlfile);
        // if file_get_contents fails to open the link do nothing
        if(!$original_file) {}
        else {
            // find words in original file contents
            preg_match_all("/<hw>(.*?)<\/hw>(.*?)<def>(.*?)<\/def>/", $original_file, $results);
            $blocks = $results[0];
            // traverse blocks array
            for ($j = 0; $j <= count($blocks)-1; $j++) {
                preg_match_all("/<hw>(.*?)<\/hw>/", $blocks[$j], $wordarray);
                $words = $wordarray[0];
                $word = addslashes(strip_tags($words[0]));
                $word = preg_replace('{-}', ' ', $word);
                $word = preg_replace("/[^a-zA-Z0-9\s]/", "", $word);
                preg_match_all("/<def>(.*?)<\/def>/", $blocks[$j], $definitionarray);
                $definitions = $definitionarray[0];
                $definition = addslashes(strip_tags($definitions[0]));
                $definition = preg_replace('{-}', ' ', $definition);
                $definition = preg_replace("/[^a-zA-Z0-9\s]/", "", $definition);
                preg_match_all("/<pos>(.*?)<\/pos>/", $blocks[$j], $posarray);
                $poss = $posarray[0];
                $pos = addslashes(strip_tags($poss[0]));
                $pos = preg_replace('{-}', ' ', $pos);
                $pos = preg_replace("/[^a-zA-Z0-9\s]/", "", $pos);
                preg_match_all("/<fld>(.*?)<\/fld>/", $blocks[$j], $fldarray);
                $flds = $fldarray[0];
                $fld = addslashes(strip_tags($flds[0]));
                $fld = preg_replace('{-}', ' ', $fld);
                $fld = preg_replace("/[^a-zA-Z0-9\s]/", "", $fld);

                $insertsql = "INSERT INTO gcide (word, definition, pos, fld) VALUES ('$word', '$definition', '$pos', '$fld')";
                $insertresult = mysql_query($insertsql) or die(mysql_error());

                echo $word. " " . $definition ."\n";
            }
        }
    }
    echo 'Done!';
?>

CSS For Search Page - gcide.css

body{ font-family:Arial, Helvetica, sans-serif; }
#search_box { padding:4px; border:solid 1px #666666; margin-bottom:15px; width:300px; height:30px; font-size:18px;-moz-border-radius: 6px;-webkit-border-radius: 6px; }
#search_results { display:none;}
.word { font-weight:bold; }
.found { font-weight: bold; }
dl {    font-family:serif;}
dt {    font-weight:bold;}
dd {    font-weight:normal;}
.pos {    font-weight: normal;}
.fld {    margin-right:10px;}

HTML for Search Page - index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>PHP, jQuery search of GCIDE</title>
        <link href="gcide.css" rel="stylesheet" type="text/css"/>
        <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/ui-lightness/jquery-ui.css" rel="stylesheet" type="text/css"/>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
        <script type="text/javascript">
            $(function() {
                $("#search_box").keyup(function() {
                    // getting the value that user typed
                    var searchString    = $("#search_box").val();
                    // forming the queryString
                    var data            = 'search='+ searchString;
                    // if searchString is not empty
                    if(searchString) {
                        // ajax call
                        $.ajax({
                            type: "POST",
                            url: "gcide_search.php",
                            data: data,
                            beforeSend: function(html) { // this happens before actual call
                                $("#results").html('');
                                $("#search_results").show();
                                $(".word").html(searchString);
                            },
                            success: function(html){ // this happens after we get results
                                $("#results").show();
                                $("#results").append(html);
                            }
                        });
                    }
                    return false;
                });
            });
        </script>
    </head>
    <body>
        <div class="ui-widget-content" style="padding:10px;">
            <input id="search_box" class='search_box' type="text" />
            <div id="search_results">Search results for <span class="word"></span></div>
            <dl id="results"></dl>
        </div>
    </body>
</html>

PHP for jQuery Search - gcide_search.php

<?php
    if (isset($_POST['search'])) {
        $db = new pdo("mysql:host=localhost;dbname=fiddle", "root", "");
        // never trust what user wrote! We must ALWAYS sanitize user input
        $word = mysql_real_escape_string($_POST['search']);
        $query = "SELECT * FROM gcide WHERE word LIKE '" . $word . "%' ORDER BY word LIMIT 10";
        $result = $db->query($query);
        $end_result = '';
        if ($result) {
            while ( $r = $result->fetch(PDO::FETCH_ASSOC) ) {
                $end_result                 .= '<dt>' . $r['word'];
                if($r['pos'])   $end_result .= ',&nbsp;<span class="pos">'.$r['pos'].'</span>';
                $end_result                 .= '</dt>';
                $end_result                 .= '<dd>';
                if($r['fld'])   $end_result .= '<span class="fld">('.$r['fld'].')</span>';
                $end_result                 .= $r['definition'];
                $end_result                 .= '</dd>';
            }
        }
        if(!$end_result) {
            $end_result = '<dt><div class="ui-state-highlight ui-corner-all" style="margin-top: 20px; padding: 0 .7em;">
            <p><span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>
            No results found.</p>
            </div></dt>';
        }
        echo $end_result;
    }
?>

这篇关于如何使用 PHP 在 GCIDE XML 中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆