Search code examples
phppreg-match

How to preg_match these HTML tags?


I have this HTML file 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>

In displayItems.php, I would like to use preg_match to find the item(s) that has/have the name="Designed by X091" and get it's price and contentId, and its hair set and the data.

With preg_match is it possible? Thanks :)


Solution

  • For this you do not want to use regular expressions, as the potential for erroneous parsing is too great. Instead you should use parsing library, like SimpleXML or similar.

    Then you can use a simple loop, to check for the name attribute. Something like this, in other words:

    $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.
    }