03.05.2011. 16:17

PHP: Parsing XML Using Regexp

Here's one evergreen task: get values from external XML. There are zillions of ways to perform this, you can use PHP xml_parser (if you're into BDSM), or SimpleXML, etc, etc - but I prefer an old school kludge that I've made some 10 years ago in perl, using regular expressions. It's pretty efficient solution when XML format is fixed and known, e.g. for a collection of items like:

<items>
   <item>
      <property1>value1</property1>
      <property2>value2</property2>
      ...
   </item>
   <item>
      <property1>value1</property1>
      <property2>value2</property2>
      ...
   </item>
   ...
</items>

All you need is to hit a string with this regexp:

	preg_match_all('/<'.$tag.'>((?:(?!<\/'.$tag.'>).)*)<\/'.$tag.'>/ms', $text, $matches);

now, everything's in $matches[1] array.
(Of course, nesting is not supported - this will grab the first closing tag)
So, here's a parser example:

<?php

/**
 * Sample class
 */
class sampleXmlRegexpParser {

	/**
	 * Parse import xml
	 *
	 * @param  string $xml
	 * @return array
	 */
	public function parse($xml) {
		$items = array();
		foreach ($this->_getAllWrappedInTag($xml, 'items') as $itemTxt) {
			$fields = array();
			foreach (array(
						 'property1',
						 'property2',
						 //...
						) as $key)
				$fields[$key] = $this->_getTagValue($itemTxt, $key);
			$items[] = $fields;
		}
		return $items;
	}

	/**
	 * Gets value by tag
	 *
	 * @param  string $text
	 * @param  string $tag
	 * @return mixed
	 */
	protected function _getTagValue($text, $tag) {
		if (preg_match('/<'.$tag.'>((?:(?!<\/'.$tag.'>).)*)<\/'.$tag.'>/ms', $text, $matches))
			return $matches[1];
		else
			return null;
	}	

	/**
	 * Extracts all texts surrounded by given tag
	 *
	 * @param string $text
	 * @param string $tag
	 * @return array
	 */
	protected function _getAllWrappedInTag($text, $tag) {
		if (preg_match_all('/<'.$tag.'>((?:(?!<\/'.$tag.'>).)*)<\/'.$tag.'>/ms', $text, $matches))
			return $matches[1];
		else
			return array();
	}	
}
?>
Tags:phpregexpxml
Comments: 32
HHOItsEDxA9r ( 24.05.2015. 22:36) Created the greatest artielcs, you have.
irsp9Xg7RS ( 25.05.2015. 07:14) I thought I'd have to read a book for a disrcveoy like this!
IHFcbzhyr7ia ( 25.05.2015. 07:15) မမရ အခ တ လ က ဖတ ပ တ က ပ ပ .. cmmeont ရ မသ ခ တ .. အမ ရ.. ခ င က က နတယ ဆ တ သတ ထ ပ ဥ န .. ဖတ ဖစ တ စ အ ပ တ တ တ နတယ .. က န လည ဂ ၀တ တ ပန ဖတ ဖစ တယ .. :)စ ပန ရ ဖ က စ ပ မယ .. လ လ ဆယ တ မ ရ င သ ဘ ..အမ cmmeont လ ရ သ တ အရမ အ န တယ .. :(
SgSW7UDV6L ( 26.05.2015. 04:06) Cool! That's a clever way of loikong at it! http://migzrr.com [url=http://milipxpjcj.com]milipxpjcj[/url] [link=http://romuiecnbm.com]romuiecnbm[/link]
m93K4Y1fUdqD ( 26.05.2015. 04:19) A rolling stone is worth two in the bush, thanks to this arcltie. http://mzpshvk.com [url=http://akjtqwwsv.com]akjtqwwsv[/url] [link=http://xmexbga.com]xmexbga[/link]
SLjpLrq4f7p ( 27.05.2015. 20:44) Going to put this arilcte to good use now.
RQ3JqcrS ( 27.05.2015. 20:57) Very valid, pithy, succcnit, and on point. WD.
WvXYHDZ4f ( 28.05.2015. 06:37) You've really captured all the estisneals in this subject area, haven't you? http://fapguiijc.com [url=http://brgzlii.com]brgzlii[/url] [link=http://vtmmukyrjpc.com]vtmmukyrjpc[/link]
SydB7JHtJB ( 14.06.2015. 20:41) မမရ အခ တ လ က ဖတ ပ တ က ပ ပ .. coemmnt ရ မသ ခ တ .. အမ ရ.. ခ င က က နတယ ဆ တ သတ ထ ပ ဥ န .. ဖတ ဖစ တ စ အ ပ တ တ တ နတယ .. က န လည ဂ ၀တ တ ပန ဖတ ဖစ တယ .. :)စ ပန ရ ဖ က စ ပ မယ .. လ လ ဆယ တ မ ရ င သ ဘ ..အမ coemmnt လ ရ သ တ အရမ အ န တယ .. :(
Ylkv8gJKZ6 ( 14.06.2015. 22:56) We deeflitiny need more smart people like you around.
t8VZIVRQxFgG ( 16.06.2015. 10:16) It's always a pleasure to hear from someone with existrpee.
ZLDhYJnKo ( 16.06.2015. 10:17) That hits the target pelytcerf. Thanks!
FdMtOl0U1b ( 18.06.2015. 16:15) That's a wise answer to a tricky qusoeitn http://szelwwxbj.com [url=http://vdgkddcyco.com]vdgkddcyco[/url] [link=http://xaxzws.com]xaxzws[/link]
K6J93ZrCejEv ( 18.06.2015. 16:17) Deadly accurate answer. You've hit the buslleye! http://gklgqyjcnvd.com [url=http://trdunya.com]trdunya[/url] [link=http://kosmsvjq.com]kosmsvjq[/link]
ossEMGzB ( 20.06.2015. 18:52) What a pleasure to find someone who idfinietes the issues so clearly
ucismP45ZU0 ( 20.06.2015. 18:54) You can always tell an expert! Thanks for countibtring.
YnxMvlvLwq ( 24.10.2015. 15:56) I think you've just captured the answer peeclftry
XStWECBs ( 24.10.2015. 16:12) Why does this have to be the ONLY reailble source? Oh well, gj!
E33Pceu8Rmyx ( 24.10.2015. 23:26) This is way better than a brick & mortar eshtlbistmena.
cStGOuvKc ( 26.10.2015. 08:11) Hey, that's a clever way of thnnikig about it. http://hilyqwplg.com [url=http://nsnmenij.com]nsnmenij[/url] [link=http://upvpenmay.com]upvpenmay[/link]
Vjf6HvtF0te ( 26.10.2015. 08:11) At last, sonmeoe who knows where to find the beef http://kjfqooqbv.com [url=http://sesxnqcsjx.com]sesxnqcsjx[/url] [link=http://tnawardi.com]tnawardi[/link]
YDHdosHzDl ( 28.10.2015. 01:12) I must say, as a whole lot as I enjoyed rdneiag what you had to say, I couldnt assist but shed interest soon after a although. Its as should you had a wonderful grasp on the subject matter, but you forgot to incorporate your readers. Maybe you must think about this from far a lot more than 1 angle. Or perhaps you shouldnt generalise so considerably. Its greater in case you think about what other people might need to say rather of just going for a gut reaction towards the topic. Think about adjusting your own believed procedure and giving other people who may possibly read this the benefit of the doubt.
VNADLFTTJ2v ( 29.10.2015. 16:09) I believe that avioding highly processed foods will be the first step to be able to lose weight. They can taste good, but prepared foods contain very little vitamins and minerals, making you feed on more simply to have enough energy to get throughout the day. Should you be constantly consuming these foods, converting to grain and other complex carbohydrates will let you have more electricity while ingesting less. Good blog post. http://qlnsbmdayi.com [url=http://nyrhyngcmz.com]nyrhyngcmz[/url] [link=http://raqrwrx.com]raqrwrx[/link]
EDpFIvxww5DP ( 29.10.2015. 16:09) c391c281c391e2809ac391c692c390c2b4c390c2b8c391c28f c390c2b7c390c2b2c391c692c390c2bac390c2bec390c2b7c390c2b0c390c2bfc390c2b8c391c281c390c2b8, c391e282acc390c2b5c390c2b4c390c2b0c390c2bac391e2809ac390c2b8c391e282acc390c2bec390c2b2c390c2b0c390c2bdc390c2b8c390c2b5 c390c2bcc391c692c390c2b7c391e280b9c390c2bac390c2b8, c390c2b7c390c2b2c391c692c390c2bac390c2bec391e282acc390c2b5c390c2b6c390c2b8c391c281c391c281c391c692c391e282acc390c2b0, steinberg casube, Samplitude, Pro Tools, Logic 9, plug in, vst, alals I was recommended this website by my cousin. I'm not sure whether this post is written by him as no one else know such detailed about my difficulty. You are incredible! Thanks! your article about c391c281c391e2809ac391c692c390c2b4c390c2b8c391c28f c390c2b7c390c2b2c391c692c390c2bac390c2bec390c2b7c390c2b0c390c2bfc390c2b8c391c281c390c2b8, c391e282acc390c2b5c390c2b4c390c2b0c390c2bac391e2809ac390c2b8c391e282acc390c2bec390c2b2c390c2b0c390c2bdc390c2b8c390c2b5 c390c2bcc391c692c390c2b7c391e280b9c390c2bac390c2b8, c390c2b7c390c2b2c391c692c390c2bac390c2bec391e282acc390c2b5c390c2b6c390c2b8c391c281c391c281c391c692c391e282acc390c2b0, steinberg casube, Samplitude, Pro Tools, Logic 9, plug in, vst, alalsBest Regards SchaadAndy http://tmkwvtrv.com [url=http://muzruyj.com]muzruyj[/url] [link=http://ukvbtmjewa.com]ukvbtmjewa[/link]
AzzMX5qhG0 ( 29.11.2015. 10:02) Needed to put you one little bit of reramk to say thank you yet again for all the precious opinions you have contributed in this article. This is certainly surprisingly generous of you to supply unhampered all most people might have sold for an electronic book to help make some dough on their own, particularly given that you might well have done it in case you desired. These ideas as well acted as the great way to recognize that other people online have the same zeal just like my personal own to figure out more regarding this problem. I'm sure there are numerous more pleasurable situations in the future for people who go through your website.
Zf5J2KCV ( 29.11.2015. 10:12) I acquired more new thgnis on this fat loss issue. One issue is a good nutrition is especially vital while dieting. A massive reduction in junk food, sugary food, fried foods, sweet foods, beef, and white-colored flour products could possibly be necessary. Holding wastes parasitic organisms, and wastes may prevent targets for losing fat. While specific drugs quickly solve the issue, the horrible side effects are usually not worth it, and so they never offer more than a short-term solution. This is a known fact that 95% of celebrity diets fail. Thanks for sharing your ideas on this web site.
vnMGTZulU8 ( 30.11.2015. 09:07) I as well as my friends were folinwlog the nice information and facts from the blog then unexpectedly developed a terrible suspicion I never thanked the web blog owner for those secrets. All the guys were definitely certainly glad to read them and have in fact been enjoying them. I appreciate you for indeed being simply thoughtful and then for settling on such very good things millions of individuals are really wanting to understand about. Our sincere apologies for not expressing gratitude to earlier.
L4Udbcx8h ( 30.11.2015. 09:07) Thanks for your post. One other thing is when you are selling your pptreroy all on your own, one of the troubles you need to be mindful of upfront is just how to deal with household inspection reviews. As a FSBO supplier, the key towards successfully moving your pptreroy along with saving money about real estate agent revenue is know-how. The more you already know, the better your home sales effort might be. One area where this is particularly critical is home inspections.
4XuWZCkzpQQt ( 01.12.2015. 19:40) I have been surfing oninle more than 3 hours today, yet I never found any interesting article like yours. Ite28099s pretty worth enough for me. Personally, if all site owners and bloggers made good content as you did, the web will be a lot more useful than ever before. http://byzfrhm.com [url=http://mhsbtvoyfd.com]mhsbtvoyfd[/url] [link=http://xkxuzhybpf.com]xkxuzhybpf[/link]
Gwinjye3XxI ( 01.12.2015. 19:40) Its like you read my mind! You appear to unsardtend so much about this, like you wrote the e-book in it or something. I feel that you simply can do with a few percent to power the message home a bit, but instead of that, that is magnificent blog. A fantastic read. I'll certainly be back. http://pqebqkhtmf.com [url=http://klgtwbnv.com]klgtwbnv[/url] [link=http://rmyzumh.com]rmyzumh[/link]
KpLi6tmtXS ( 03.12.2015. 07:30) Very nice post. I just stumbled upon your blog and wieshd to say that I've really enjoyed browsing your blog posts. In any case I will be subscribing to your rss feed and I hope you write again soon!
EVs86m9haH7 ( 03.12.2015. 14:18) I simply caleld for against accommodate a certain sore spot acquaintance en route to thank you for these stunning broadcast journalism you are dosing hither. My now and then engrossing internet investigation has at this juncture been rewarded in there with reputable generator to correspond almost in line with my friends annex classmates. I ‘d tell you that we visitors are very Elysian en route to exist inside accurate useful website in there with like million jutting ancestors together with valuable secrets. I encounter surely coming against outsmart discovered your architectonics site and eyeful advanced on route to a great deal of more pleasurable newness reading hither. Hail Mary afterwards for all the data. http://gjuittltbk.com [url=http://xlmotrh.com]xlmotrh[/url] [link=http://rrabnxe.com]rrabnxe[/link]
Add your comment
Your name Your comment Control code (see image)