Я пытаюсь создать окно живого поиска на моем веб-сайте. У меня есть XML файл для базы данных. У меня есть часть JavaScript, но я новичок на PHP и имею некоторые проблемы с этим кодом, который я нашел в w3schools. Мой вопрос заключается в том, как изменить следующий код, чтобы получить только значение тега "name"?
PHP-код:
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("links.xml");
$x=$xmlDoc->getElementsByTagName('link');
//get the q parameter from URL
$q=$_GET["q"];
//lookup all links from the xml file if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<($x->length); $i++)
{
$y=$x->item($i)->getElementsByTagName('title');
$z=$x->item($i)->getElementsByTagName('url');
if ($y->item(0)->nodeType==1)
{
//find a link matching the search text
if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))
{
if ($hint=="")
{
$hint="<a href='" .
$z->item(0)->childNodes->item(0)->nodeValue .
"' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
}
else
{
$hint=$hint . "<br /><a href='" .
$z->item(0)->childNodes->item(0)->nodeValue .
"' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
}
}
}
}
}
// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}
//output the response
echo $response;
?>
XML:
<books>
<book>
<name>Harry Potter</name>
<quantity> 50 </quantity>
<price>19.90</price>
</book>
<book>
<name>Casino Royale</name>
<quantity> 50 </quantity>
<price>12.99</price>
</book>
<book>
<name>The Great Gatsby</name>
<quantity> 40 </quantity>
<price>14.90</price>
</book>
</books>
Заранее благодарю за ваши ответы! Я очень ценю вашу помощь!
Вот пример того, как вы это сделаете:
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("links.xml");
$books = $xmlDoc->getElementsByTagName("book");
//get the q parameter from URL
$q = $_GET["q"];
//lookup all links from the xml file if length of q>0
if (strlen($q) > 0) {
$hint = "";
foreach ($books as $book) {
$name = $book->getElementsByTagName("name")->item(0)->nodeValue;
$price = $book->getElementsByTagName("price")->item(0)->nodeValue;
$quantity = $book->getElementsByTagName("quantity")->item(0)->nodeValue;
echo "$name - $price - $quantity<br/>";
}
}
Это напечатает $name
, $price
и $quantity
из xml файла для каждой книги.