tags:

views:

54

answers:

1

I am trying to make a search function using the combination of DOM, PHP and XML. I got something up and running but the problem is that my search function will only accept exact terms, on top of this am wondering if the method I picked the most efficient

$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";    
    }
+1  A: 

As Karussell said, the best answer is to not use PHP for this. Find a library that can take care of this for you.

However, I acknowledge that this isn't always an option. With that in mind...

I think you're being a bit more verbose than you need to be. First, you should be using the DOMDocument->load($file) method for loading the file.

Then, I would probably use an XPath query to select the nodes you're looking for instead of performing the search yourself.

Your code would end up looking something like this:

$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";
}
Nycto