ページからhtmlを取得してsimplexmlオブジェクトにロードするphpが少しあります。ただし、内の要素のクラスを取得していません
php
//load the html page with curl
$html = curl_exec($ch);
curl_close($ch);
$doc = new DOMDocument();
$doc->loadHTML($html);
$sxml = simplexml_import_dom($doc);
ページhtml。$ htmlのvar_dumpを実行すると、それがスクレイピングされて$ htmlに存在することが示されます。
<li class="large">
<a style="" id="ref_3" class="off" href="#" onmouseover="highlightme('07');return false;" onclick="req('379');return false;" title="">07</a>
</li>
$ docと$ sxmlのvar_dump(下記)は、「off」のクラスが欠落していることを示しています。残念ながら、このクラスに基づいてページを処理する必要があります。
[8]=>
object(SimpleXMLElement)#50 (2) {
["@attributes"]=>
array(1) {
["class"]=>
string(16) "large"
}
["a"]=>
string(2) "08"
}
simplexml_load_file
およびを使用してxpath
、インラインコメントを参照してください。
あなたが求めているのは、本当に、あなたが必要な要素を見つけたら、これです
$row->a->attributes()->class=="off"
そして、以下の完全なコード:
// let's take all the divs that have the class "stff_grid"
$divs = $xml->xpath("//*[@class='stff_grid']");
// for each of these elements, let's print out the value inside the first p tag
foreach($divs as $div){
print $div->p->a . PHP_EOL;
// now for each li tag let's print out the contents inside the a tag
foreach ($div->ul->li as $row){
// same as before
print " - " . $row->a;
if ($row->a->attributes()->class=="off") print " *off*";
print PHP_EOL;
// or shorter
// print " - " . $row->a . (($row->a->attributes()->class=="off")?" *off*":"") . PHP_EOL;
}
}
/* this outputs the following
Person 1
- 1 hr *off*
- 2 hr
- 3 hr *off*
- 4 hr
- 5 hr
- 6 hr *off*
- 7 hr *off*
- 8 hr
Person 2
- 1 hr
- 2 hr
- 3 hr
- 4 hr
- 5 hr
- 6 hr
- 7 hr *off*
- 8 hr *off*
Person 3
- 1 hr
- 2 hr
- 3 hr
- 4 hr *off*
- 5 hr
- 6 hr
- 7 hr *off*
- 8 hr
*/
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加