2015-01-16 3 views
1

예를 들어 더 이상 태그가없는 주 div로 콘텐츠를 가져오고 싶습니다. "Harvard Pilgrim HealthCare에서 가져온 Winter Skate, 하루 제공 올 겨울의 캐빈 열풍에 대한 완벽한 치료법입니다. " 내가 여기에 간단한 HTML DOM과 XPath를 사용하고있어 내 코드간단한 HTML DOM이있는 Xpath는 태그의 텍스트()를 가져올 수 없습니다.

foreach($dom->find('//*[@id="main"]/text()[1]') as $element){ 
    $details=$element; 
} 

이지만 어느 쪽도 모든 요소를 ​​점점 나 foreach 문으로 이동합니다. 해결책을 제안 해 주시겠습니까?

<div id="main"> 
    <div>a</div> 
    <div>b</div> 
    <div>c</div> 
    <a name="abc"></a>Winter Skate brought to you by Harvard Pilgrim HealthCare, offering day and evening public skating, is the perfect remedy to cabin fever this winter.<br /> 
    <br /> 
    A fun and affordable activity for parents with children, Winter Skate is also an ideal lunch break getaway and a romantic addition to a dinner date at Patriot Place. <br /> 
    <br /> 
    The 60-by-140-foot, refrigerated ice surface is designed specifically for recreational skating and the professional surface is large enough to accommodate beginners and experts alike.<br /> 
    <br /> 
    On-site skate rentals, concessions and bathrooms are available and parking is free.<br /> 
    <br /> 
    <br /> 
    <b>Concessions</b><br /> 
    Dunkin Donuts will be on-site with coffee, hot chocolate and donuts available for purchase. Additionally, Patriot Place features 16 dining and quick service restaurants including: Bar Louie, Baskin Robbins, Blue Fin Lounge, CBS Scene, Davio’s, Five Guys Burgers, Godiva, Olive Garden, Qdoba, Red Robin, Skipjack’s, Studio 3, Tastings Wine Bar & Bistro, Tavolino Pizza Gourmet, Twenty8 Food & Spirits.<br /> 
    <br /> 
    NOTE: Hours may occasionally vary due to inclement weather, Patriots home games, or pre-scheduled private events – please check back or call 508-203-2100<br><br> 
    <a name='hours' class='ranchor'></a> 
</div> 
+0

thanks cwallenpoole. –

답변

1

SimpleHtmlDom은 공식 W3C DOM API를 구현하지 않습니다. XPath가 아닌 CSS 선택기를 사용합니다. CSS 선택자는 텍스트 노드를 선택하는 데 사용할 수 없으며 요소 노드 만 일치시킵니다.

당신은 PHPs 표준, 기본 DOM 확장을 사용할 수 있습니다

$dom = new DOMDocument(); 
@$dom->loadHtml($html); 

$xpath = new DOMXPath($dom); 
var_dump(
    $xpath->evaluate('string(//*[@id="main"]/text()[normalize-space() != ""][1])') 
); 

출력 :

string(149) "Winter Skate brought to you by Harvard Pilgrim HealthCare, offering day and evening public skating, is the perfect remedy to cabin fever this winter." 

[normalize-space() != ""] 필터 노드가 공백을 포함하는 조건이다.

string()은 결과 목록의 첫 번째 노드를 문자열로 변환하고 루프가 필요 없습니다.

DOMDocument::loadHTML()DOMDocument::loadHTMLFile() 잘못된 html 소스를 복구하려고합니다. 예를 들어 htmlbody이 없으면 추가합니다. 이 새로운 구조를 얻을 수있는 문자열로 다시 HTML을 저장하는 것이 좋습니다 이렇게하면 HTML을 변경할 수 있습니다

$html = <<<'HTML' 
<div id="main" class="one" class="two"> 
    <div>a</div> 
    <div>b</div> 
    <div>c</div> 
    <a name="abc"></a>Winter Skate brought to you by ... 
HTML; 

$dom = new DOMDocument(); 
@$dom->loadHtml($html); 
echo $dom->saveHtml(); 

출력 :에서

또한
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> 
<html><body><div id="main" class="one"> 
    <div>a</div> 
    <div>b</div> 
    <div>c</div> 
    <a name="abc"></a>Winter Skate brought to you by ...</div></body></html> 

에서 @ 블록 오류 및 경고 HTML 구문 분석. 이것은 대부분의 시간을 작동하지만 더 좋은 방법은 오류를 기록 /를 libxml 기능을 사용하여 처리하는 것입니다

$dom = new DOMDocument(); 
libxml_use_internal_errors(TRUE); 
$dom->loadHtml($html); 

var_dump(libxml_get_errors()); 

출력 : 빈 소스를보고하면, 당신은 확인해야

array(1) { 
    [0]=> 
    object(LibXMLError)#2 (6) { 
    ["level"]=> 
    int(2) 
    ["code"]=> 
    int(42) 
    ["column"]=> 
    int(39) 
    ["message"]=> 
    string(26) "Attribute class redefined 
" 
    ["file"]=> 
    string(0) "" 
    ["line"]=> 
    int(1) 
    } 
} 

DOMDocument :: loadHTMLFile이 가져올 수있는, file_get_contents() 함께 얻으려고.

+0

실제로 문제는 웹 사이트가 제대로 형성되지 않았기 때문에 웹 사이트가 DOMXPath에 의해 지정된 방식으로 HTML을로드하지 않는다는 것입니다 (예 : 웹 사이트에서 클래스 속성을 태그에 두 번 정의했습니다. 다음 줄에서 볼 수 있습니다). 그런 다음 DOMDocument 대신 간단한 HTML DOM 객체를 사용하기 시작했습니다.

+0

당신은 방법을 사용하여 간단한 DOM 객체의 형태로 솔루션을 제안 할 수 있습니까? –

+0

아니요, 제가 말했던 것처럼 : CSS 선택자는 텍스트 노드를 가져올 수 없습니다. 그러나 DOM :: loadHtml()은 HTML을 수정하려고합니다. 'echo $ dom-> saveHtml();'을 시도하고 어떻게 변경되는지 확인하십시오. – ThW

관련 문제