(PHP)基于浏览器语言设置导入XML值

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?

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']");