2016-08-19 77 views
1

我构建了一个脚本,该脚本应为我的项目生成站点地图。strtr()部分不工作

此脚本使用strtr()来替换不需要的标志并转换德语元音变音。

$ers = array('<' => '', '>' => '', ' ' => '-', 'Ä' => 'Ae', 'Ö' => 'Oe', 'Ü' => 'Ue', 'ä' => 'ae', 'ö' => 'oe', 'ü' => 'ue', 'ß' => 'ss', '&' => 'und', '*' => '', ' - ' => '-', ',' => '', '.' => '', '!' => '', '?' => ''); 
foreach ($rs_post as $row) { 
    $kategorie = $row['category']; 
    $kategorie = strtr($kategorie,$ers); 
    $kategorie = strtolower($kategorie); 
    $kategorie = trim($kategorie); 
    $org_file .= "<url><loc>https://domain.org/kategorie/" . $kategorie . "/</loc><lastmod>2016-08-18T19:02:42+00:00</lastmod><changefreq>monthly</changefreq><priority>0.2</priority></url>" . PHP_EOL; 
} 

像“<”不受欢迎的迹象将被正确替换,但德国的变音不转换。我不知道为什么。

有人对我有一个tipp吗?

Torsten

+1

最有可能的原因是字符集差异 –

回答

0

正如其他人指出,最可能的原因是一个字符编码不匹配。由于您试图转换的标题显然是UTF-8,所以问题很可能是您的PHP源代码不是。尝试将文件重新保存为UTF-8文本,并查看是否可以解决问题。

顺便说一句,一个简单的方法来调试这将是打印出你的数据行和你的音译数组到相同的输出文件,使用例如。 print_r()var_dump(),并查看输出以查看其中的非ASCII字符是否正确。如果字符在数据中看起来正确但在音译表中错误(反之亦然),则表示编码不匹配。

Ps。如果您安装了PHP iconv扩展程序(可能的话),请考虑using it to automatically convert your titles to ASCII.

+0

非常感谢,@ Ilmari-Karonen ......这是我的解决方案。它现在有效! – bee

0

检查字符集。 如果您的发送表单页使用:

<meta charset="utf-8"> 

将不起作用。

尝试使用其他的编码像

<meta charset="ISO-8859-1"> 

这里是一个小样本代码来测试您更换阵列:

<!DOCTYPE html> 
<html> 
<?php 
if(isset($_POST["txt"])) 
{ 
    echo '<head><meta charset="ISO-8859-1"></head><body>'; 

    $posted = $_POST["txt"]; 
    echo 'Received raw: ' . $posted .'<br/>'; 
    echo 'Received: ' . htmlspecialchars($posted).'<br/>';; 

    $ers = array('<' => '', '>' => '', ' ' => '-', 'Ä' => 'Ae', 'Ö' => 'Oe', 'Ü' => 'Ue', 'ä' => 'ae', 'ö' => 'oe', 'ü' => 'ue', 'ß' => 'ss', '&' => 'und', '*' => '', ' - ' => '-', ',' => '', '.' => '', '!' => '', '?' => ''); 

    $replaced = strtr($posted,$ers); 
    echo 'Replaced: ' . $replaced .'<br/>'; 
} 
else { 
    ?> 
<head> 
    <!--<meta charset="utf-8">--> <!--THIS ENCODING WILL NOT WORK --> 
    <meta charset="ISO-8859-1"> <!--THIS WORKS FINE --> 
</head> 
<body> 
    <p>the text you want to replace here</p> 
    <form action="#" method="post"> 
    Text: <input type="text" name="txt" value=""> 
    <input type="submit" value="Submit"> 
</form> 

<?php 
} 
?> 
</body> 
</html> 
+0

...或者更好的办法是将脚本文件保存为UTF-8文本。 –