1

I am building a Live Search function on my website, I used the W3schools example, which worked perfectly. But I want to use MySQL database instead of the XML file, so I am working on a code to take the MySQL database and turn it into an XML file.

   <?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;

  ?> 

I am getting this error:

 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 

I have read the explanation at: Avoid DOMDocument XML warnings in php But I have no idea how to fix that in my code. Any suggestions?

4

1 回答 1

0

这将从您的 mysql 表中的“名称”列中获取数据并将其放入一个数组中,该数组与您键入时 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;
}
于 2015-10-19T20:15:06.230 回答