我使用cURL从数据库中获取数据,并将其保存在变量($alter)中。
接下来,读取文本文件。这是用一定次数的循环完成的。因此,从文本文件中读取一行并将其写入变量"$linex“。然后将变量"$linex“与变量"$alter”进行比较,然后与第二行进行比较,以此类推。
但不幸的是,它并不像描述的那样起作用。每一行都输出"false“,即使字符串必须匹配。
代码中的错误在哪里?
<?php
header('Content-type: text/html; charset=utf-8');
$User_Agent = 'Mozilla/5.0 (Windows NT 6.1; rv:60.0) Gecko/20100101 Firefox/60.0';
$id = $_POST["id"];
$id2 = $_POST["klass"];
$id3 = $_POST["element"];
$url2 = "https://bpk.bs.picturemaxx.com/api/v1/editing/classifications/$id2/elements";
$request_headers = [];
$request_headers[] = 'Accept: application/json';
$request_headers[] = 'charset=utf-8';
$request_headers[] = 'Content-Type: application/json; charset=utf-8';
$request_headers[] = 'Accept-Encoding: gzip, deflate, identity';
$request_headers[] = 'Accept-Language: de,en-US;q=0.7,en;q=0.3';
$request_headers[] = 'X-picturemaxx-api-key: key';
$request_headers[] = 'Authorization: Bearer key';
$ch = curl_init($url2);
curl_setopt($ch, CURLOPT_USERAGENT, $User_Agent);
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING, "");
$result = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$data = json_decode($result, true);
$alternativnameze = array();
foreach($data['items'] as $alternativ) {
$alternativname = $alternativ['localized'];
$alternativnamez = $alternativname['de-de'];
$alternativnameze[] = $alternativnamez['classification_element_name'];
}
$alter = substr(implode($alternativnameze),0 ,1000000);
$file = 'name_test.txt';
$fh = fopen($file, 'r');
if ($fh === false) {
die('Could not open file: '.$file);
}
for ($i = 0; $i < 6; $i++) {
$linex = fgets($fh);
if (strpos($alter, $linex) !== false) {
echo 'true<br />';
} else {
echo 'false<br />';
}
}
if (fclose($fh) === false) {
die('Could not close file: '.$file);
}
?>
变量"$alter“的外部示例
C.S. Lewis,29.11.1898 - 22.11.1963,(Clive Staples-Lewis;Clive Staples Lewis;C.S. Luis;C. Hamilton;C. S. Ruisu;Klajv S. L.L.ʹjuis;Klaĭ诉S. L.ʹI︠u︡is;Clive S. Lewis;Clive Staples Lewis;Jack Lewis;C.S. Luis;N.W.办事员;C.S. Lewis)
变量"$linex“的输出示例,它应该作为一个子字符串与整个字符串"$alter”进行比较。
C. S. Lewis,29.11.1898 - 22.11.1963
非常感谢所有的提示和解决方案建议。
发布于 2018-11-26 16:18:51
在比较之前尝试使用$linex = rtrim($linex, "\r\n");
来处理文件中可能出现的额外行尾字符。
发布于 2018-11-26 16:18:08
fgets
使用新行chararcter从文件中返回一行。因此,如果文本文件中的一行只是一个a
,fgets($fh);
将返回a\n
(在Linux中,其他操作系统上的字符不同)。strpos("a b c", "a\n")
将始终返回false。
trim
应该能做到这一点:
$linex = trim(fgets($fh));
https://stackoverflow.com/questions/53484679
复制相似问题