dsh1956 2014-08-27 10: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 11: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']");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧