2013-07-17 4 views
1

cURL을 사용하여 HTML 페이지를 가져옵니다. html 페이지에는 이와 같은 테이블이 있습니다.PHP를 사용하여 HTML에서 값 추출

<table class="table2" style="width:85%; text-align:center"> 
<tr> 
<th>Refference ID</th> 
<th>Transaction No</th> 
<th>Type</th> 
<th>Operator</th> 
<th>Amount</th> 
<th>Slot</th> 
</tr> 
<tr> 
<td>130717919020ffqClE0nRaspoB</td> 
<td>8801458920369</td> 
<td>Purchase</td> 
<td>Visa</td> 
<td>50</td> 
<td>20130717091902413</td> 
</tr> 
</table> 

이 페이지는 HTML 페이지의 유일한 테이블입니다. 나는 PHP를 사용하여 Refference ID & 슬롯을 추출해야한다.

하지만 어떻게 할 수 있는지 잘 모릅니다.

편집 : 이 one 나에게 많은 도움이되었습니다. 허용 대답 같은

+6

부부, 이것은 또한 도움이 될 수 phpquery – DevZer0

+2

http://php.net/manual/en/function.stripos .php –

+1

@Jose David Garcia Llanos :'stripos'를 사용하여 어떻게하는지보고 싶습니다. – zerkms

답변

0
$str = '<table class="table2" style="width:85%; text-align:center"> 
<tr> 
<th>Refference ID</th> 
<th>Transaction No</th> 
<th>Type</th> 
<th>Operator</th> 
<th>Amount</th> 
<th>Slot</th> 
</tr> 
<tr> 
<td>130717919020ffqClE0nRaspoB</td> 
<td>8801458920369</td> 
<td>Purchase</td> 
<td>Visa</td> 
<td>50</td> 
<td>20130717091902413</td> 
</tr> 
</table>'; 

preg_match_all('/<td>([^<]*)<\/td>/', $str, $m); 

$reference_id = $m[1][0]; 
$slot = $m[1][5]; 
+2

작동하지만, 정규 표현식을 사용하여 HTML 코드를 구문 분석하는 것은 매우 바람직하지 않습니다. 적절한 HTML 구문 분석기를 사용해야합니다. PHP는 DOMDocument 클래스와 같은 내장 된 파서와 함께 제공됩니다. – Shane

+1

@Shane 물론! 나는 "일을 끝내기"위해 - 심지어 베스트 프랙티스에 대해서조차도 다음 사람만큼 유죄입니다. 프로젝트의 규모와 중요성에 따라 이것은 터무니없는 대답 일 수 있습니다. –

+1

나는 또한 이것에 유죄입니다. 그것은 효과가있다. 그러나 나는 낙심하고 있다고 생각했다. 만약 작은 스크립트 나 그와 비슷한 것이라면, 반드시 규칙을 지키십시오. 그러나 이것이 프로덕션 환경에서 사용되도록 의도 된 것이라면, 작업을 수행하는 올바른 방법을 살펴볼 것을 제안합니다.) – Shane

1

정규식 기반 솔루션은 HTML 문서에서 정보를 추출 할 수있는 올바른 방법 하지입니다.

사용이 대신 같은 DOMDocument 기반 솔루션 : 당신을위한 키워드, XPath는, simplehtmldom의

$str = '<table class="table2" style="width:85%; text-align:center"> 
<tr> 
<th>Refference ID</th> 
    ... 
<th>Slot</th> 
</tr> 
<tr> 
<td>130717919020ffqClE0nRaspoB</td> 
    ... 
<td>20130717091902413</td> 
</tr> 
</table>'; 

// Create a document out of the string. Initialize XPath 
$doc = new DOMDocument(); 
$doc->loadHTML($str); 
$selector = new DOMXPath($doc); 

// Query the values in a stable and easy to maintain way using XPath 
$refResult = $selector->query('//table[@class="table2"]/tr[2]/td[1]'); 
$slotResult = $selector->query('//table[@class="table2"]/tr[2]/td[6]'); 

// Check if the data was found 
if($refResult->length !== 1 || $slotResult->length !== 1) { 
    die("Data is corrupted"); 
} 

// XPath->query always returns a node set, even if 
// this contains only a single value. 
$refId = $refResult->item(0)->nodeValue; 
$slot = $slotResult->item(0)->nodeValue; 

echo "RefId: $refId, Slot: $slot", PHP_EOL; 
관련 문제