PHP foreach in foreach problem
I want to insert some value from first and second foreach into database, but I met some trouble. I write my problem in the code. I can not solve the two loop problem. I ask for a help.
<?php
header('Content-type:text/html; charset=utf-8');
set_time_limit(0);
require_once ('../conn.php');
require_once ('../simple_html_dom.php');
$url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&q=obama&key={api-key}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
$body = curl_exec($ch);
curl_close($ch);
$data = json_decode($body);
foreach ($data->responseData->results as $resul开发者_如何学JAVAt) {
$title = html_entity_decode($result->titleNoFormatting);
$link = html_entity_decode($result->unescapedUrl);
$html = @file_get_html($link );
foreach(@$html->find('h3') as $element) {
$table=$element;
echo $table;// here while the $table is empty, echo is null.
}
echo $table;// here while the $table is empty, echo will repeat the prev $table value.
mysql_query("SET NAMES utf8");
mysql_query("INSERT INTO ...");// I want insert all the $title and $table into database.
}
echo '<hr />';
}
?>
I print the result while the $table is empty, echo will repeat the prev $table value
.
Organizing for America | BarackObama.com
Barack Obama - Wikipedia, the free encyclopedia
President Barack Obama | The White House
President Obama Nominates William Francis Kuntz, II to the United States District Court//the prev value
Change.gov - The Official Web Site of the
President Obama Nominates William Francis Kuntz, II to the United States District Court//here the $table is empty, it will repeat the prev $table value, and it should be empty.
Barack Obama on Myspace
Idle Friends▼
ob (obama) on Twitter
Piè di pagina
Barack Obama
Advertise with the NY Daily News!
Barack Obama on the Issues
Voting Record
PHP's variable initialization and scoping rules are kind of funny.
At no point are you initializing $table
. It first gets referenced two foreach
es deep. PHP allows this, and won't complain about it.
The problem is that you're constantly trying to set it to a value, but you're never actually resetting it.
Initialize it to null
before the inner foreach
:
$html = file_get_html($link );
$table = null; // <-- New!
foreach($html->find('h3') as $element) {
$table = $element;
echo $table;
}
This ensures that, when the foreach
is completed, $table
will either be null
, or it will be the final H3 element in the HTML document you fetched. (Incidentally, if you really did want the final H3, you can probably just grab the array that find
returns and look at the last element rather than looping through.)
Also, please get rid of the @
error-silencing operators, turn error_reporting
all the way up, and make sure you've turned on display_errors
. You may have other errors lurking that you are intentionally ignoring, and that leads to horror stories.
精彩评论