为什么我的查询在PHP中执行时会增加额外的空间?

时间:2018-04-23 14:16:08

标签: php html mysqli rendering

我已经坐了一个简单的Curl导航到一个页面,并将结果保存在一个字符串中。目标是从页面获取地址(包含在特定的html标记中),然后将其保存到我的服务器上的数据库

$url = "http://www.odensebolig.dk/property/vindegade-128-lejl-nr-115-5000-odense-c/";
$agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, "http://www.google.dk");
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type:application/x-www-form-urlencoded"));
$result = curl_exec($ch);

然后我在2个html标签之间找到一个地址,并将结果保存在一个变量中。示例:" Vindegade 128,lejl。 NR。 115,5000 Odense C"。我在stackoverflow上找到了一个函数,我用它。然后我将字符串拆分为带有地址,邮编和城镇的数组,并最终查询更新地址表中的地址:

function get_string_between($string, $start, $end) {
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0)
        return '';
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}

//To get the full adress i do this
$full_adress = get_string_between($result, '<h4>', '</h4>');
//And the result:
echo $full_adress; //Vindegade 128, lejl. nr. 115, 5000 Odense C

//Find last comma
$last_comma = strrpos($full_adress, ',');
//Save all text before last comma
//And here i have tried removing all kinds of line breaks, and trim trailing and endeing spaces
$adress['adress'] = preg_replace("/\r|\n/", "", trim(substr($full_adress, 0, $last_comma)));
$adress['zip'] = substr($full_adress, ($last_comma + 2), 4);
$adress['town'] = substr($full_adress, ($last_comma + 7));
//And the result of [adresse]:
echo $adress['adress']; //Vindegade 128, lejl. nr. 115
//I then put the info in a query
$query = "UPDATE adresses SET `adress` = '". $adress['adress'] ."' WHERE `url` = '$url'";
//Go!
if($objCon->query($query)){
    echo 'Done';//Done
}

现在奇怪的是,在我的地址表中,网址的记录正在变为:&#34; Vindegade 128,lejl。 NR。 115&#34; (在&#34; Vindegade&#34;和&#34; 128&#34;之间有一个额外的空间)。为什么?如果我回应我的查询,并手动将其插入phpmyadmin,记录不会更新额外的空间

1 个答案:

答案 0 :(得分:2)

原始HTML

<h4>Vindegade  128, lejl. nr. 115, 5000 Odense C</h4>
直接从您链接的页面复制

包含您提到的位置中的两个空格(在“Vindegade”和“128”之间)。由于我使用格式化代码显示来显示原始字符串,因此您可以看到空格。

然而,如果我直接粘贴它,以便浏览器解释和呈现HTML,如下所示,即使它在HTML源代码中也是如此。

Vindegade 128,lejl。 NR。 115,5000 Odense C.

因此,如果您正如您所描述的那样,您使用PHP将原始HTML回显到网页中,然后将您的浏览器中的输出复制/粘贴到另一个程序(例如phpMyAdmin)中,那么这将解释其中的差异。浏览器通常只显示原始HTML中任何一组连续空格中的第一个,因此在运行查询之前,您复制的版本将被剥离其第二个空间(由浏览器的渲染引擎),而发送到mySQL的版本直接来自你的PHP将不会有这种待遇。

总而言之,您所遇到的只是浏览器处理HTML文档中空格的副作用。

N.B。如果将上面的两个示例字符串从浏览器窗口粘贴到文本编辑器中,您也会看到差异。