我正在尝试使用DOM,PHP和XML的组合来创建搜索功能。我得到了一些东西并且正在运行,但问题是我的搜索功能只接受确切的术语,除此之外我想知道我选择的方法是否最有效
$searchTerm = "Lupe";
$doc = new DOMDocument();
foreach (file('musicInformation.xml')as $node)
{
$xmlString .= trim($node);
}
$doc->loadXML($xmlString);
$records = $doc->documentElement->childNodes;
$records = $doc->getElementsByTagName("musicdetails");
foreach( $records as $record )
{
$artistnames = $record->getElementsByTagName("artistname");
$artistname = $artistnames->item(0)->nodeValue;
$recordnames = $record->getElementsByTagName("recordname");
$recordname = $recordnames->item(0)->nodeValue;
$recordtypes = $record->getElementsByTagName("recrodtype");
$recordtype = $recordtypes->item(0)->nodeValue;
$formats = $record->getElementsByTagName("format");
$format = $formats->item(0)->nodeValue;
$prices = $record->getElementsByTagName("price");
$price = $prices->item(0)->nodeValue;
if($searchTerm == $artistname|| $searchTerm == $recordname || $searchTerm == $recordtype ||$searchTerm == $format || $searchTerm == $price)
{
echo "$artistname - $recordname - $recordtype - $format -$price\n";
}
答案 0 :(得分:2)
正如Karussell所说,最好的答案是不要使用PHP。找到一个可以为您解决此问题的图书馆。
但是,我承认这并不总是一种选择。考虑到这一点......
我认为你比你需要的更加冗长。首先,您应该使用DOMDocument->load($file)方法来加载文件。
然后,我可能会使用XPath query来选择您要查找的节点,而不是自己执行搜索。
您的代码最终会看起来像这样:
$searchTerm = "text";
$doc = new DOMDocument();
$doc->load( 'musicInformation.xml' );
$xpath = new DOMXPath( $doc );
$result = $xpath->query(
'//musicdetails[ .//text()[contains( ., "'. addslashes($searchTerm) .'" )] ]'
);
echo "Found: ". $result->length ."\n";
foreach ( $result AS $node ) {
echo $doc->saveXML($node) ."\n\n";
}