使用Mysql和PHP进行实时搜索

时间:2012-12-07 21:31:33

标签: mysql xml domdocument

我正在我的网站上建立一个实时搜索功能,我使用了W3schools的例子,它运作得很好。但我想使用MySQL数据库而不是XML文件,因此我正在研究一个代码来获取MySQL数据库并将其转换为XML文件。

   <?php

  header("Content-type: text/xml");

    include 'dbc.php';

      $query = "SELECT * FROM airports";
      $result = mysql_query($query, $link)
      or die('Error querying database.');

  $xml_output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
  $xml_output .= "<entries>\n";

  for($x = 0 ; $x < mysql_num_rows($result) ; $x++){
      $row = mysql_fetch_assoc($result);
      $xml_output .= "\t<entry>\n";
      $xml_output .= "\t\t<ident>" . $row['ident'] . "</ident>\n";
          // Escaping illegal characters
          $row['name'] = str_replace("&", "&", $row['name']);
          $row['name'] = str_replace("<", "<", $row['name']);
          $row['name'] = str_replace(">", "&gt;", $row['name']);
          $row['name'] = str_replace("\"", "&quot;", $row['name']);
      $xml_output .= "\t\t<name>" . $row['name'] . "</name>\n";
      $xml_output .= "\t</entry>\n";
  }

  $xml_output .= "</entries>";

  echo $xml_output;

  ?> 

我收到此错误:

 Warning: DOMDocument::load() [domdocument.load]: Start tag expected, '<' not found in /public_html/sql2xml.php, line: 11 in /public_html/livesearch.php on line 12
 no suggestion 

我在Avoid DOMDocument XML warnings in php阅读了解释 但我不知道如何在我的代码中解决这个问题。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

这将从你的mysql表中的'Name'列中获取数据并将其放入一个数组中,当你输入时,w3c学校会查找相同的数组

$mysqli = new mysqli(HOST,USER,PASSWORD,DATABASE);

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

$query = "SELECT * FROM table";
$result = $mysqli->query($query);

while($row = $result->fetch_array()) 
{
    $a[]=$row["Name"];
}

/* free result set */
$result->free();

/* close connection */
$mysqli->close();

// get the q parameter from URL
$q = $_REQUEST["q"];

$hint = "";

// lookup all hints from array if $q is different from ""
if ($q !== "") {
    $q = strtolower($q);
    $len=strlen($q);
    foreach($a as $name) {
        if (stristr($q, substr($name, 0, $len))) {
            if ($hint === "") {
                $hint = $name;
            } else {
                $hint .= ", $name";
            }
        }
    }
}

if (isset($q))
{
    // Output "no suggestion" if no hint was found or output correct values
    echo $hint === "" ? "no suggestion" : $hint;
}