2016-05-30 175 views
0

我有一個來自我想要轉換的合作伙伴的系統狀態頁,這樣我就可以將其輸入自動化到我自己的服務頁面中。該服務的狀態由<span>課程提供。我知道這很不理想,但這是他們提供更新的唯一方式。將html標籤轉換爲php數組

下面是HTML的一個副本:

<ul class="item-3"> 
    <li class="status service1"> 
     <span class="icon"></span> 
     <h6> 
     SERVICE 1 
     </h6> 
     <p> 
     Updated: 
     9:52 AM CST Apr, 24 
     </p> 
     <span class="arrow up"></span> 
    </li> 
    <li class="status service2"> 
     <span class="icon"></span> 
     <h6> 
     SERVICE 2 
     </h6> 
     <p> 
     Updated: 
     9:52 AM CST Apr, 24 
     </p> 
     <span class="arrow up"></span> 
    </li> 
    <li class="status service3"> 
     <span class="icon"></span> 
     <h6> 
     SERVICE 3 
     </h6> 
     <p> 
     Updated: 
     9:52 AM CST Apr, 24 
     </p> 
     <span class="arrow up"></span> 
    </li> 
</ul> 

我需要搶<span class="arrow up">值,因爲這是服務狀態,以及<li class="status service3">,因爲這告訴我這是什麼樣的服務。

由於我的狀態頁API使用ID而不是「上/下」等我需要狀態和服務在陣列中,所以我可以將它們轉換爲我的格式。

+0

http://stackoverflow.com/questions/1592438/create-array-from-the-contents-of-div-tags-in -php –

+0

http://php.net/manual/en/function.preg-match-all.php –

回答

0
$xml = new SimpleXMLElement($html); 

$result = $xml->xpath('//ul/li'); 
$up = array(); //array of servises that is 'up' 
$down = array(); //array of servises that is 'down' 
foreach ($result as $item) 
{ 
    if (strpos($item->span[1]->attributes()->class, 'up') !== false) 
    { 
     $up[] = str_replace("status ", "", $item->attributes()->class); 
    } 

    if (strpos($item->span[1]->attributes()->class, 'down') !== false) 
    { 
     $down[] = str_replace("status ", "", $item->attributes()->class); 
    } 
} 

var_dump($up); 
var_dump($down); 

威爾輸出 「向上」 系統狀態

array(3) { 
    [0]=> 
    string(8) "service1" 
    [1]=> 
    string(8) "service2" 
    [2]=> 
    string(8) "service3" 
} 
+0

謝謝@Dumkaaa但我如何告訴這個從文件加載html? –

+0

@ red-spider簡單使用file_get_contents從其他網站加載LO: '$ html = file_get_contents('http://example.com');' 或從您的網站include_path '// <= PHP 5 $ file = file_get_contents('./ people.txt',true); //> PHP 5 $ file = file_get_contents('./ people.txt',FILE_USE_INCLUDE_PATH);' – Dumkaaa

+0

謝謝@Dumkaaa,似乎加載它,但我似乎仍然有一個問題讓這工作正確。我可以輸出整個SimpleXMLElement,但不能輸出上面顯示的數組示例。 –