| 
	
 | 
 Posted by Erwin Moller on 08/06/07 19:00 
php.developer2007@gmail.com wrote: 
> On Aug 6, 9:06 pm, Benjamin <musiccomposit...@gmail.com> wrote: 
>> On Aug 6, 9:44 am, php.developer2...@gmail.com wrote: 
>> 
>> 
>> 
>> 
>> 
>>> Hi i want to parse a xml document which contains attribute can anybody 
>>> help me in that. 
>>> Example 
>>> -------------------- 
>>> <category id="1" parent-id="1" level="2"> 
>>> <category id="2" parent-id="1" level="3"> 
>>> <category id="3" parent-id="5" level="6"> 
>>> I want to get all id's in this example with using regular 
>>> expressions.. 
>>> Output 
>>> ---------- 
>>> 1 
>>> 2 
>>> 3 
>> First of all that's not valid XML. In order to parse it, it has to be 
>> valid. This, however, is easily fixed in your case. Just put the whole 
>> body in <categories> tags and add the XML declaration like this: 
>> <?xml version="1.0"?> 
>> <categories> 
>> <category id="1" parent-id="1" level="2"> 
>> <category id="2" parent-id="1" level="3"> 
>> <category id="3" parent-id="5" level="6"> 
>> </categories> 
>> 
>> With PHP, you have many options to parse XML with. My favorite and 
>> probably the most easy is SimpleXML. Look athttp://www.php.net/simplexml.- Hide quoted text - 
>> 
>> - Show quoted text - 
>  
> Yeah I know i m just giving an example.I want it to be done with 
> preg_match_all as i had done this before with it.help if any body 
> help.I m facing problem this time. 
>  
 
Hi, 
 
If you want to do it with regexpressions, you could try something like this. 
Please note I do it in 2 steps, simply because I suck at regexp to do it  
in 1 step. 
 
Normally I do not respond to regexpression questions, because of the  
abovementioned reason, but since you need it quickly, here it comes. 
 
I tried with 'look behind' and 'look ahead' but of course that didn't  
suceed in my case. :P 
 
<?php 
 
// get your data in a var. Just an example 
$var='<category id="031" parent-id="1" level="2">\n<category id="233"  
parent-id="1" level="3">\n<category id="31" parent-id="5" level="6">'; 
 
$expr = '/\ id="[0-9]+"/'; 
 
preg_match_all($expr,$var,$results); 
 
echo "<pre>"; 
print_r($results); 
echo "</pre>"; 
 
// results now contain an array with [0] =>  id="031" , [1] =>  
id="233",  [2] =>  id="31" 
$allresultsStr = implode("",$results[0]) ; 
 
// get the numbers out 
preg_match_all('/[0-9]+/',$allresultsStr,$results2); 
 
 
echo "<pre>"; 
print_r($results2); 
echo "</pre>"; 
 
?> 
 
Regards, 
Erwin Moller
 
  
Navigation:
[Reply to this message] 
 |