我指的是我的问题的答案,答案是由@abhy提供的,有效,链接是php proDOM parsing error
我正在进一步研究它,希望将提取的数据保存到mysql数据库中......
我使用的代码是
?php
$ch = curl_init(); // create a new cURL resource
$word = 'books';
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://images.google.com/images?q=".$word."s&tbm=isch/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$data = curl_exec($ch); // grab URL and pass it to the browser
curl_close($ch);
$dom = new DOMDocument();
@$dom->loadHTML($data); // avoid warnings
$listA = $dom->getElementsByTagName('a'); // read all <a> elements
foreach ($listA as $itemA) { // loop through each <a> element
if ($itemA->hasAttribute('href')) { // check if it has an 'href' attribute
$href = $itemA->getAttribute('href'); // read the value of 'href'
if (preg_match('/^\/imgres\?/', $href)) { // check that 'href' should begin with "/imgres?"
$qryString = substr($href, strpos($href, '?') + 1);
parse_str($qryString, $arrHref); // read the query parameters from 'href' URI
echo '<br>' . $arrHref['imgurl'] . '<br>';
$sql = "INSERT INTO `p_url_imgsrch`(`id`, `word_id`, `url_imgsrch`) VALUES ('','8','$arrHref['imgurl']')";
mysql_query($sql) or die("error in updating urls") ;
}
}
}
?>
这个想法是,我将在数据库中插入从解析中提取的每个链接,我确信我的连接没问题,带有虚拟数据的相同 mysql 查询字符串正在 mysql 中工作并成功插入数据。但是我使用虚拟网址代替 '$arrHref['imgurl']'
..
我得到的错误是
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in D:\wamp\www\demo\login\abhay.php on line 24
abhay.php 是包含此代码的文件,此外,在尝试解决问题时,有时会出现类似 T_STRING 的错误...
我在哪里犯了错误?请给我一个指导..
谢谢
最佳答案
你可以使用 "{$arrHref['imgurl']}"
这样 php 就知道这是一个变量
如果您希望它自动递增,则不应插入 id:
$sql = "INSERT INTO `p_url_imgsrch`(`word_id`, `url_imgsrch`) VALUES ('8','{$arrHref['imgurl']}')";
但是,一旦 $arrHref['imgurl'] 包含单引号,这可能会导致 SQL 命令损坏。
所以更好的解决方案是使用mysql_real_escape_string
:
$imgurl = mysql_real_escape_string($arrHref['imgurl']);
$sql = "INSERT INTO `p_url_imgsrch`(`word_id`, `url_imgsrch`) VALUES ('8','{$imgurl}')";
关于PHP DOM 解析和 mysql 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8891716/