如何preg_match这些HTML标签?

时间:2016-10-11 05:31:53

标签: php preg-match

我有这个HTML文件items.php

<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>

displayItems.php中,我想使用preg_match查找拥有name="Designed by X091"的商品并获得它的价格和contentId,以及头发套装和数据。

有了preg_match吗?谢谢:))

1 个答案:

答案 0 :(得分: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.
}