2016-10-11 115 views
-1

我有這個HTML文件items.php如何preg_match這些HTML標籤?

<all> 
    <designItems base="http://website.com/cms/items/"> 
    <item price="20" contentId="10928" name="Designed by X091"> 
     <hair set="10"> 
     <data> 
      <![CDATA[ 
      [{"c":110092,"y":10,"x":34}] 
      ]]> 
     </data> 
     </hair> 
    </item> 

    <item price="90" contentId="10228" name="Designed by XXX"> 
     <hair set="2"> 
     <data> 
      <![CDATA[ 
      [{"c":110022,"y":-2,"x":90}] 
      ]]> 
     </data> 
     </hair> 
    </item> 
    </designItems> 
</all> 

在​​,我想用preg_match發現有項目(S)/有name="Designed by X091"並獲得它的價格和內容識別,它的毛髮定型和數據。

有了preg_match有可能嗎?謝謝:)

+0

當然,這是可能的。你試過什麼了? –

+0

@Magnus Eriksson我不確定從哪裏開始。關於'preg_match'搜索HTML的所有答案都有特定的HTML屬性,但我的價格和contentId屬性每次都不一樣 –

+2

這實際上並不像HTML,而是像XML。使用PHP的XML函數來讀取屬性,而不是使用'preg_match()'。在這裏閱讀關於SimpleXML:http://php.net/manual/en/simplexml.examples-basic.php –

回答

2

爲此,您不想使用正則表達式,因爲錯誤解析的可能性太大。相反,你應該使用解析庫,如SimpleXML或類似的。

然後你可以使用一個簡單的循環來檢查name屬性。換句話說:

$items = new SimpleXMLElement ($items); 

// Loop through all of the elements, storing the ones we want in an array. 
$wanted = array(); 
foreach ($items->designItems->item as $current) { 
    // Skip the ones we're not interested in. 
    if ($current['title'] != 'designed by aaaa') { 
     continue; 
    } 

    // Do whatever you want with the item here. 
}