views:

163

answers:

1

I have a PHP script that goes through an XML file, but I want to be able to search the object for a value, just like I can search an array for a value.

According to comments on PHP.net, array_search() supports objects as of PHP5, but I can't get it to work.

The XML file is a list for bus stops, and I want to be able to search through the object after a matching bus stop.

The current code looks like this, just lists the stops:

$xml = new SimpleXMLElement(file_get_contents("StopPointList.xml"));

foreach ($xml->StopPoint as $stop)
{
    echo $stop->StopName.'<br />';
}

And for reference, the bus stop XML file looks like this:

<?xml version="1.0" encoding="ISO-8859-1"?>
<StopPointList NetworkVersion="20080828">
    <StopPoint>
        <DISID>3012086:2</DISID>
        <PositionNumber>2</PositionNumber>
        <StopPointName>2</StopPointName>
        <StopName>Sinsenveien</StopName>
    </StopPoint>
    <StopPoint>
        <DISID>2160364:2</DISID>
        <PositionNumber>2</PositionNumber>
        <StopPointName>2</StopPointName>
        <StopName>Rogneskjær</StopName>
    </StopPoint>
</StopPointList>

I would like to be able do a MySQL-like search like this: %search%

How can I do this?

+2  A: 

I would say that's what XPath (the spec/a tutorial) was made for.

For example: To find all stop points with a name that contains "Sinsen", this would be the XPath expression to use:

//StopPoint[contains(StopName, 'Sinsen')]

In PHP you can use SimpleXML (SimpleXMLElement::xpath) to do it.

Tomalak
That seems to work! Thanks! But I have another question. How do I make the search case-insensitive? :)
rebellion
This is excellent material for your next Stack Overflow question. :-)
Tomalak
Oh, and do not forget to mention that you want a solution that works for non-English alphabets.
Tomalak