You're here: Home / PHP /

Converting Tag's Properties Into Associative Array

The Problem

You've fetched an HTML page and you want to read a tag and its properties from the page. Maybe the HTML looks something like this:

<div id="container">
<img id="photo" src="img/myphoto.gif" border="0" width="50" height="60" alt="my cool photo" />
</div>
<p>Some text here</p>

And your code needs to read the properties of the <img> tag. You need to convert the properties to an associative array like this:

Array
(
  [id] => photo
  [src] => img/photo
  [border] => 0
  [width] => 50
  [height] => 60
  [alt] => my cool photo
)

The Solution

This is the code to solve the problem above. To solve your own problem, do some hacking to it.

<?php
$string = '
<div id="container">
 <img id="myphoto" src="img/myphoto.gif"  border="0" width="50" height="60" alt="my cool photo" />
</div>
<p>some text here</p>';

/* get <img ...> */
preg_match("/(<img[^>]+>)/", $string, $a);

/* get properties of <img ...> */
preg_match_all("/([\w]+=\"[\w\/\.]+\")/", $a[1], $b);

/* replace key='val' to key=val */
$c = preg_replace("/([\w]+)=\"([\w\/\.]+)\"/", "$1=$2", $b[1]);

/* convert obtained string to associative array */
foreach($c as $line) {
    list($key, $val) = explode('=', $line);
    $props[$key] = $val;
}

/* now we have:
$props = Array
(
    [id] => myphoto
    [src] => img/myphoto.gif
    [border] => 0
    [width] => 50
    [height] => 60
)*/
?>

Keywords: tag to array, html tags, associative array, php

Share:  del.icio.us logo Save to del.icio.us  digg logo Digg this!

comment.gifAdd your comment

(required, will not be published) (optional)