1

sample.php

<?
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'],0,2);
header("Content-Type: text/html; charset=UTF-8");
$dom = new DOMDocument();
$xml_string = file_get_contents("sample.xml");
$dom->loadXML($xml_string);
$xpath = new DOMXPath($dom);
$xpath->registerNamespace('xml', 'http://www.w3.org/XML/1998/namespace');
$res1 = $xpath->query('//item[@name="tree"]/value[@xml:lang="en"]');
echo $res1->item(0)->nodeValue ."<br/>"; // Success
$res2 = $xpath->query('//item[@name="tree"]/value[@xml:lang="$lang"]');
echo $res2->item(0)->nodeValue ."<br/>"; // Failed
?>

sample.xml

<?xml version="1.0" encoding="UTF-8"?>
<lang>
    <item name="tree">
        <value xml:lang="en"><![CDATA[banana]]></value>
        <value xml:lang="es"><![CDATA[plátano]]></value>
        <value xml:lang="ru"><![CDATA[банан]]></value>
    </item>
</lang>

I think, do not recognize the variable lang: xml. Is there a better way which creates a multi-lingual site?

canfas
  • 59
  • 5
  • There are some other ways on how to create a multilingual site here: http://stackoverflow.com/questions/2806886/most-efficient-approach-for-multilingual-php-website – Patrick G Aug 27 '14 at 11:33

1 Answers1

0

Actually your problem is not quite complicated. Currently, you're using single quotes and therefore they are single quoted string literals so variables will not be interpreted.

$res2 = $xpath->query('//item[@name="tree"]/value[@xml:lang="$lang"]');

Use double quotes instead:

$res2 = $xpath->query("//item[@name='tree']/value[@xml:lang='$lang']");
Kevin
  • 41,694
  • 12
  • 53
  • 70