Search code examples
phpxmlxpathsimplexml

Dictionary by XML file


We have a XML dictionary file like this:

<?xml version="1.0" encoding="UTF-8"?>
<words>
    <word>
        <phrase lang="IR">حسابدار</phrase>
        <phrase lang="FR">Comptable</phrase>
        <phrase lang="CN">会计</phrase>
        <phrase lang="US">Accountant</phrase>
    </word>
    <word>
        <phrase lang="IR">حسابرس</phrase>
        <phrase lang="FR">Auditeur</phrase>
        <phrase lang="CN">核数师</phrase>
        <phrase lang="US">Auditor</phrase>
    </word>
    <word>
        <phrase lang="IR">مهندس</phrase>
        <phrase lang="FR">Ingénieur</phrase>
        <phrase lang="CN">工程师</phrase>
        <phrase lang="US">Engineer</phrase>
    </word>
</words>

We need a PHP code that find the text containing "ginee" (Engineer) and return that French translate (Ingénieur).

Our PHP code is

<?php
$xml = simplexml_load_file("test.xml");
$nodes = $xml->xpath('//word/phrase[contains(..,"ngin")]');
var_dump($nodes);
?> 

and it return

array(4) { [0]=> object(SimpleXMLElement)#2 (2) { ["@attributes"]=> array(1) { ["lang"]=> string(2) "IR" } [0]=> string(10) "مهندس" } [1]=> object(SimpleXMLElement)#3 (2) { ["@attributes"]=> array(1) { ["lang"]=> string(2) "FR" } [0]=> string(10) "Ingénieur" } [2]=> object(SimpleXMLElement)#4 (2) { ["@attributes"]=> array(1) { ["lang"]=> string(2) "CN" } [0]=> string(9) "工程师" } [3]=> object(SimpleXMLElement)#5 (2) { ["@attributes"]=> array(1) { ["lang"]=> string(2) "US" } [0]=> string(8) "Engineer" } } 

Solution

  • Since you already got the nodes you want from the query you used, just access the property (the french FR) using ->attributes():

    Basic idea:

    $nodes = $xml->xpath('//word/phrase[contains(..,"ngin")]');
    $lang_needed = 'FR';
    $result = '';
    if(!empty($nodes)) {
        foreach($nodes as $node) {
            if((string) $node->attributes()->lang === $lang_needed) {
                // $result = (string) $node;
                echo $node;
            }
        }
    }
    

    You could also devise your query this way:

    $lang_needed = 'FR';
    $nodes = $xml->xpath("//word/phrase[contains(..,'A')][@lang = '{$lang_needed}']");
    if(!empty($nodes as $node)) {
        // $result = (string) $node;
        echo $node;
    }