Help With Searching XML File By Attribute

I’m putting a live search feature on my site that searches through an XML file. Here is a small sample of my xml file:

links.xml

[code]<?xml version="1.0" encoding="UTF-8"?>

0 29 ** warehouse:03 score desc 0 300 GENERAL MI Baking Mixes NABISCO Misc. Baking Products [/code]

And here is the php file:
[php]<?php // RAY_temp_martinbros.php
error_reporting(E_ALL);

// MAKE AN OBJECT
$obj = SimpleXML_Load_File(“links.xml”);

// IF THERE IS A URL REQUEST PARAMETER
$q = isset($_GET[‘q’]) ? $_GET[‘q’] : NULL;
if (!$q) die(‘No request’);

// THE RESPONSE STRING
$hint = NULL;

// USE AN ITERATOR TO FIND PROPERTIES AND ATTRIBUTES
foreach ($obj->result->doc as $doc)
{
// ACQUIRE BOTH ATTRIBUTES
$b = (string)$doc->str[0];
$c = (string)$doc->str[1];

// IF EITHER CONTAINS THE QUERY STRING
if ( (stripos($b, $q) !== FALSE) || (stripos($c, $q) !== FALSE) )
{
    $hint .= "<br/>$b<br/>$c<br/>";
}

}
if (empty($hint)) echo “No suggestion”;
$hint = substr($hint, 5);
$hint = rtrim($hint, ‘
’);
echo $hint;[/php]

OK, so this actually works as-is, however, this script relies on “positional” data instead of the name="" attribute. And this is a problem because the child elements can vary in number.

What I’m looking for is a way to grab the node value by attribute (for example; name=“brand”). I’ve tried using xpath, but I’m still fairly new to this stuff and couldn’t get it working correctly. Oh, and I can’t just change the tag names of the XML file. That’s the way SOLR creates the file so that’s what I’m stuck with. Any ideas? I’ve been pulling my hair out on this one! Thanks!!

Using the code below, you can determine the attribute name and plug in your logic from there.

[php]foreach ($obj->result->doc as $doc)
{
foreach ($doc->str as $str)
{
echo ‘print out doc’;
echo ‘

’;
echo print_r($str);
echo ‘
’;
echo '
attribute = ’ . $str->attributes() . ‘
’;
echo ‘end printing out doc
’;
}

}
[/php]

Use this to see the attribute name for each string. I think the attributes method might return an array if there is more than one attribute, so handle accordingly. Use this page for more reference. http://php.net/manual/en/simplexmlelement.attributes.php

Sponsor our Newsletter | Privacy Policy | Terms of Service