user3884108
user3884108

Reputation: 1

SimpleXML, find parent node by searching value

I downloaded a french->english dictionnary to translate a french request (one word request) in english.

For example, a user typing "voiture" (car in french) in the search input will be translate in "car", and "car" will be search in my database (invisible for user, he think looking for "voiture").

So this is a piece of the dictionnary :

SimpleXMLElement Object
(
[entry] => Array
    (
        ...
        ... 
        [7] => SimpleXMLElement Object
            (
                [form] => SimpleXMLElement Object
                    (
                        [orth] => ADN
                        [pron] => ad
                    )

                [gramGrp] => SimpleXMLElement Object
                    (
                        [pos] => n
                        [gen] => masc
                    )

                [sense] => SimpleXMLElement Object
                    (
                        [def] => DNA
                    )
            )
        [8] => SimpleXMLElement Object
            (
                [form] => SimpleXMLElement Object
                    (
                        [orth] => Abkhasie
                        [pron] => abkazi
                    )

                [gramGrp] => SimpleXMLElement Object
                    (
                        [pos] => n
                    )

                [sense] => SimpleXMLElement Object
                    (
                        [def] => Abkhazia
                    )
            )
            ...

So, [orth] contain the french word, and [def] the english translation. I would know how its possible to search if the value of [orth] exist, and if this value exist, return the value of [def] in the SimpleXMLElement object.

Upvotes: 0

Views: 412

Answers (1)

benJ
benJ

Reputation: 2580

Something like this might suffice. I've mocked up the XML from your post as wasn't sure on the original structure, but you should get the idea of the xpath query:

$languageXml = <<<XML
    <entries>
        <entry>
            <form>
                <orth>ADN</orth>
            </form>
            <sense>
                <def>DNA</def>
            </sense>
        </entry>
        <entry>
            <form>
                <orth>poisson</orth>
            </form>
            <sense>
                <def>fish</def>
            </sense>
        </entry>
        <entry>
            <form>
                <orth>voiture</orth>
            </form>
            <sense>
                <def>car</def>
            </sense>
        </entry>
    </entries>
XML;

$xml = new SimpleXMLElement($languageXml);    
$searchTerm = 'voiture';

if($result = $xml->xpath("entry/form/orth[.='$searchTerm']/../../sense")) {
    echo $result[0]->def;
};

Upvotes: 2

Related Questions