php foreach issue
I'm using simple_html_dom_helper so do some screen scraping and am encountering some errors.
The second foreach runs 4 times (since sizeof($pages) == 4
), while it should only run once. I got this code from an example script where table.result-liste
occurs several times on the page. In my case it only occurs once, so imho there is no need for a foreach. The print_r($data)
prints out the same thing 4 times and there's no need for that.
Further down I'm trying to do the same without the foreach but it just prints out no
, so there seems to a different response and am not sure why.
foreach( $pages as $page )
{
$p = $this->create_url($codes[0], $price, $page); //pass page number along
$p_html = file_get_html($p);
$row = $p_html->find("table[class=result-liste] tr");
//RUNS OK BUT NO NEED TO DO IT FOUR TIMES.
//CLASS RESULT-LISTE ONLY OCCURS ONCE ANYWAY
foreach( $p_html->find("table[class=result-liste] tr") as $row)
{
//grab only rows where there is a link
if( $row->find('td a') )
{
$d_price = $this->get_price($row->first_child());
$d_propid = $this->get_prop_id($row->outertext);
$data = array(
"price" => $d_price,
"prop_id" => $d_propid
);
print_r($data);
}
}
//MY ATTEMPT TO AVOID THE SECOND FOREACH DOES NOT WORK ...
$row = $p_html->find("table[class=result-liste] tr");
开发者_运维技巧 if( is_object($row) && $row->find('td a')) print "yes ";
else print "no ";
}
Even though the table[class=result-liste]
only occurs once on your page, this find statement is looking for the <tr>
elements that are the table's rows. So unless your table has only one row, you will need this foreach
.
$p_html->find("table[class=result-liste] tr")
Your code
foreach( $p_html->find("table[class=result-liste] tr") as $row)
{
//grab only rows where there is a link
if( $row->find('td a') )
{
$d_price = $this->get_price($row->first_child());
$d_propid = $this->get_prop_id($row->outertext);
$data = array(
"price" => $d_price,
"prop_id" => $d_propid
);
print_r($data);
}
}
Replace above code by MY code
$asRow = $p_html->find("table[class=result-liste] tr");
$row = $asRow[0];
//grab only rows where there is a link
if( $row->find('td a') )
{
$d_price = $this->get_price($row->first_child());
$d_propid = $this->get_prop_id($row->outertext);
$data = array(
"price" => $d_price,
"prop_id" => $d_propid
);
print_r($data);
}
Try with this.
精彩评论