Reputation: 57
I have string that contains area map and some other info:
$string = 'something here
<map name="map">
< area shape="circle" coords="34,210,3" alt="something 1" href="test.php?place=aaa&time=1" />
< area shape="circle" coords="34,220,3" alt="something2" href="test.php?place=bbb&time=2" />
< area shape="circle" coords="669,229,3" alt="some 8" href="test.php?place=bbb&time=3" />
</map>';
How can I get coordinates, place and time extracted from string for each area?
Upvotes: 2
Views: 210
Reputation: 76405
This looks like markup to me, why don't you simply parse it?
$DOM = new DOMDocument();
$DOM->loadXML($string);
$areas = $DOM->getElementsByTagName('area');
$coordinates = array();
for ($i = 0, $j = count($areas);$i<$j;$i++)
{
array_push($areas, $areas[$i]->getAttribute('coords'));
}
That's the way you should treat markup, IMO - unless of course you're looking forward to the end of times
See how you can make your life easier when parsing markup, that's what the docs are for.
As @SalamanA pointed out, treating a fragment as an entire DOM could be considered overkill. Thankfully, there is such a thing as a DOMFragment class which can be used in just such a case.
$DOMFragment = new DOMDocumentFragment();
$DOMFragment->appendXML($string);
//or, when you need to treat multiple DOMFragments:
$DOM = new DOMDocument();//can be used as a sort-of DOMFragment factory
$fragment = $DOM->createDocumentFragment();
$fragment2 = $DOM->createDocumentFragment();
$fragment->appendXML($string);
Upvotes: 2
Reputation: 7715
Try this out, I used regex to extract the variables into an array. You can see the results with the var_dump.
$string = 'something here
<map name="map">
< area shape="circle" coords="34,210,3" alt="something 1" href="test.php?place=aaa&time=1" />
< area shape="circle" coords="34,220,3" alt="something2" href="test.php?place=bbb&time=2" />
< area shape="circle" coords="669,229,3" alt="some 8" href="test.php?place=bbb&time=3" />
</map>';
preg_match_all("/(\d+\,\d+\,\d+)/", $string, $coords);
preg_match_all("/place\=(.*)\&time\=(\d+)/i", $string, $place_time);
var_dump($place_time, $coords);
var_dump() results
array (size=3)
0 =>
array (size=3)
0 => string 'place=aaa&time=1' (length=16)
1 => string 'place=bbb&time=2' (length=16)
2 => string 'place=bbb&time=3' (length=16)
1 =>
array (size=3)
0 => string 'aaa' (length=3)
1 => string 'bbb' (length=3)
2 => string 'bbb' (length=3)
2 =>
array (size=3)
0 => string '1' (length=1)
1 => string '2' (length=1)
2 => string '3' (length=1)
array (size=2)
0 =>
array (size=3)
0 => string '34,210,3' (length=8)
1 => string '34,220,3' (length=8)
2 => string '669,229,3' (length=9)
1 =>
array (size=3)
0 => string '34,210,3' (length=8)
1 => string '34,220,3' (length=8)
2 => string '669,229,3' (length=9)
You would access the information in the above example by array/key:
echo $coords[1][0]; //return: 34,210,3
echo $place_time[1][0]; //return: aaa
echo $place_time[2][0]; //return: 1
Upvotes: 4