i get data with cURL from a database and save it in a variable ($alter).
Next, a text file is read. This is done with a loop a certain number of times. Thereby a line is read from a textfile and written to the variable "$linex". The variable "$linex" should then be compared with the variable "$alter. Then the comparison with the second line takes place and so on.
But unfortunately it doesn't work as described. A "false" is always output for every line, even if the string has to match.
Where is the error in the code?
<?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);
}
?>
Outoput example for variable "$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ʹjuis ; Klaĭv S. Lʹi︠u︡is ; Clive S. Lewis ; Clive Staples Lewis ; Jack Lewis ; C.S. Luis ; N.W. Clerk ; C.S. Lewis)
Output example for variable "$linex" which should be compared as a substring with the whole string "$alter"
C. S. Lewis, [29.11.1898 - 22.11.1963]
Many thanks in advance for all hints and solution suggestions.
Try $linex = rtrim($linex, "\r\n");
prior to the comparison to handle extra line-ending characters which are likely in your file.