Hanpan
Hanpan

Reputation: 10251

How to search an XML payload?

I'm trying to add some quick and simple search functionality to a site. The site has an XML file with all their stores, and I want to create a search box to search for the closest store to the user by town or postcode.

I have put all the data into an array, but as far as I can tell, there is no way to 'search' an array (NOT array_search) to retrieve results like using a MySQL LIKE query.

Surely there must be a way? Using MySQL isn't an option in this case.

Upvotes: -1

Views: 565

Answers (5)

Moshin
Moshin

Reputation: 191

You could try something like this:

$q = $_GET['search'];

$file = new DOMDocument();
$file->load("filename.xml");

$xml = simplexml_import_dom($file);
foreach($xml->store as $store) 
{
  $store_name = $store->name;
  if($q == $store_name)
  {
    //query in your database
  }
}

Upvotes: 0

mario
mario

Reputation: 145472

Three options:

  • As your source is XML, you could use QueryPath or phpQuery to filter the initial data set.
  • If MySQL is not an option, you could still use a SQLite in-memory database, if you really want to use LIKE.
  • Or time tested and most simple: just manually loop over your array and do manual comparisons.

Upvotes: 3

prodigitalson
prodigitalson

Reputation: 60413

I think your best bet here is to actually load the XML into a DOM object (DOMDocument or SimpleXML) and then use its XPath impelemntation. Its not SQL but its a lot less work than writing your own algorithm that consumes the array. Especially if you are talking about performing real distance calculations like you might with an SQL platform.

Upvotes: 2

Brad Christie
Brad Christie

Reputation: 101594

I think you're looking for something like LINQ but in a PHP environment. Unfortunately I don't know of any solution like this. Best solution I can see is a custom search with a foreach and your own search parameters. Or just store the information in SQL and avoid trying to emulate it.

Upvotes: 1

KingCrunch
KingCrunch

Reputation: 131811

You can try *array_filter()* with an user defined callback.

Upvotes: 2

Related Questions