简体   繁体   中英

Using Simple HTML Dom PHP

Ok i have a bit of a problem and hope someone can help me out.

I'm using Simple HTML Dom PHP Class and trying to grab info from another site example below.

$html = file_get_html("http://example.com");
$find_country = $html->find('div[class=inline] span', 0);
if (!empty($find_country)) {
    $country = $find_country->plaintext;
} else {
    $country = '';
}

Now on the site where this code gets the info from there are two that are the same example below

<div class="inline">
    <h3>Country:</h3>
    <span>USA</span>
</div>

<div class="inline">
    <h3>Run Time:</h3>
    <span>120 min</span>
</div>

Now i only want to grab the Country but some times the Country is not available and it ends up getting the run time so could i use

<h3>Country:</h3>

Part to stop this could someone please help me out thanks.

The setup:

$html = <<<EOF
<div class="inline">
    <h3>Run Time:</h3>
    <span>120 min</span>
</div>

<div class="inline">
    <h3>Country:</h3>
    <span>USA</span>
</div>
EOF;

$doc = str_get_html($html);

Using simple you need to jump through some hoops

foreach($doc->find('h3') as $h3){
  if($h3->text() == 'Country:'){
    $country = $h3->next_sibling()->text();
    break;
  }
}

Using advanced you can get there with css:

$country = $doc->find('h3[text="Country:"] + span', 0)->text();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM