dsh1956 2014-08-27 02:05
浏览 33
已采纳

(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?

  • 写回答

1条回答 默认 最新

  • dsapkqaduj6718493 2014-08-27 03:25
    关注

    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']");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部