2016-10-11 114 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. 
}