PHP,cURL,strpos-逐行比较文本文件中的子字符串与变量中的字符串

时间:2018-11-26 15:47:59

标签: php loops curl strpos

我从数据库中使用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],(克莱夫·斯台普斯-刘易斯;克莱夫   斯台普斯刘易斯; C. S.路易斯;汉密尔顿; C. S.瑞素;克拉夫·S。   Lʹjuis; KlaĭvS. Lʹi︠u︡is;克莱夫S。刘易斯;克莱夫斯台普斯刘易斯;   杰克刘易斯;路易斯(C.S. Luis);净重文员; C.S. Lewis)

变量“ $ linex”的输出示例,应将其作为子字符串与整个字符串“ $ alter”进行比较

  

C。刘易斯,[29.11.1898-22.11.1963]

在此先感谢您提供所有提示和解决方案建议。

2 个答案:

答案 0 :(得分:0)

fgets从文件返回一行,并带有新的行字符。因此,如果文本文件中的一行只是a,则fgets($fh);将返回a\n(在Linux中,其他操作系统上的字符不同)。 strpos("a b c", "a\n")将始终返回false。

trim应该可以解决问题:

$linex = trim(fgets($fh));

答案 1 :(得分:0)

在比较之前尝试$linex = rtrim($linex, "\r\n");处理文件中可能存在的额外行尾字符。