How to parse HTML to search for content specific needles - html

Given the NSString below which was originally converted from a CData object retrieved from parsing an XML document with NSXMLParser, how can I obtain the following properties of the book: title, book image cover, author , price, and rating?
Here is my rudimentary solution for obtaining the following properties
Book Title - I could probably obtain this by looking at the riRssTitle span class, but then I would have to figure out how to read the title between the ahref url tag to obtain the title
Book Image - I would have to get by grabbing the first URL http://ecx.images-amazon.com/images/I/41Lg22K3ViL._SL160_PIsitb-sticker-arrow-dp,TopRight,12,-18_SH30_OU02_.jpg and then leaving everything up to http://ecx.images-amazon.com/images/I/41Lg22K3ViL omitting the rest, and then appending the .jpg tag to have a complete url for image retrieval at a later point.
Book Author - I'd have to follow the same step as step 1 but instead searching for the riRssContributor span tag.
Book Price - Here there is no price tag thats common across all items, one thing I do see in common though is that the price is always in a font tag where it then sits in a BOLD tag.
Rating - which can probably be retrieved by looking for the URL that contains the word stars and then grab the numbers that follow it, 4 means 4 stars, any number with -5 appended to it means an extra .5 stars. so 3-5 would mean 3.5 stars.
Whats the best way of doing this without it getting messy? Also I dont like how my code can break should Amazon decide to change the way it displays it's URLS, my app relies on amazon maintaining its url naming conventions.
For now though, is this the best way forward? Is there a quick parser that can achieve what I wish to do?
This is an example of an amazon RSS feed: http://www.amazon.co.uk/gp/rss/bestsellers/books/72/ref=zg_bs_72_rsslink
Here is the below CData NSString data I retrieve for each item.
<div style="float:left;">
<a class="url" href="http://www.amazon.co.uk/Gone-Girl-Gillian-Flynn/dp/0753827662/ref=pd_zg_rss_ts_b_72_9">
<img src="http://ecx.images-amazon.com/images/I/41Lg22K3ViL._SL160_PIsitb-sticker-arrow-dp,TopRight,12,-18_SH30_OU02_.jpg" alt="Gone Girl" border="0" hspace="0" vspace="0" />
</a>
</div>
<span class="riRssTitle">
Gone Girl
</span>
<br />
<span class="riRssContributor">
Gillian Flynn
<span class="byLinePipe">(Author)</span>
</span>
<br />
<img src="http://g-ecx.images-amazon.com/images/G/02/x-locale/common/icons/uparrow_green_trans._V192561975_.gif" width="13" align="abstop" alt="Ranking has gone up in the past 24 hours" title="Ranking has gone up in the past 24 hours" height="11" border="0" />
<font color="green">
<strong></strong>
</font> 674 days in the top 100
<br />
<img src="http://g-ecx.images-amazon.com/images/G/02/detail/stars-4-0._V192253865_.gif" width="64" height="12" border="0" style="margin: 0; padding: 0;"/>(5704)
<br />
<br />
Buy new:
<strike>£9.07</strike>
<font color="#990000">
<b>£3.85</b>
</font>
<br />
60 used & new from
<span class="price">£2.21</span>
<br />
<br />(Visit the
Bestsellers in Crime, Thrillers & Mystery list for authoritative information on this product's current rank.)

TFHpple is definitely the library to go with to parse HTML. (>1000 stars on github)
https://github.com/topfunky/hpple
Here's the obj-c solution for that RSS feed:
NSString *stringURL = #"http://www.amazon.co.uk/gp/rss/bestsellers/books/72/ref=zg_bs_72_rsslink";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *htmlData = [NSData dataWithContentsOfURL:url];
TFHpple * doc = [[TFHpple alloc] initWithHTMLData:htmlData];
NSArray *titleElements = [doc searchWithXPathQuery:#"//span[#class='riRssTitle']/a"];
for (TFHppleElement *element in titleElements)
{
NSString *title = element.firstChild.content;
NSLog(#"title: %#", title);
}
NSArray *imageElements = [doc searchWithXPathQuery:#"//a[#class='url']/img"];
for (TFHppleElement *element in imageElements)
{
NSString *image = element.attributes[#"src"];
NSMutableArray *parts = [[image componentsSeparatedByString:#"/"] mutableCopy];
NSArray *pathParts = [parts.lastObject componentsSeparatedByString:#"."];
[parts removeLastObject];
[parts addObject:[NSString stringWithFormat:#"%#.%#",pathParts.firstObject, pathParts.lastObject]];
image = [parts componentsJoinedByString:#"/"];
NSLog(#"image: %#", image);
}
NSArray *authorElements = [doc searchWithXPathQuery:#"//span[#class='riRssContributor']/a"];
for (TFHppleElement *element in authorElements)
{
NSString *author = element.firstChild.content;
NSLog(#"author: %#", author);
}
NSArray *priceElements = [doc searchWithXPathQuery:#"//font/b"];
for (TFHppleElement *element in priceElements)
{
NSString *price = element.firstChild.content;
NSLog(#"price: %#", price);
}
NSArray *ratingElements = [doc searchWithXPathQuery:#"//img"];
for (TFHppleElement *element in ratingElements)
{
if (![element.attributes[#"src"] containsString:#"stars"])
continue;
NSArray *parts = [element.attributes[#"src"] componentsSeparatedByString:#"-"];
if (parts.count < 5) continue;
NSString *rating = [NSString stringWithFormat:#"%#.%#", parts[3], [parts[4] substringToIndex:1]];
NSLog(#"rating: %#", rating);
}
Like you said, you are at the mercy of Amazon's naming conventions.

You can use TFHpple and TFHppleElement for parsing the above data as your need.
Here is the reference for doing this.

I saw your post on the iOS developer facebook group and thought I'd give my last minute input.
Because amazon doesn't keep a strict naming convention, you have to search through the feed.
This is what I attempt to do, but then I try and make it look less hackish.
If you notice, you'll find that sometimes the feed returns missing values if you try to scour for specific path names, so I've tried to make up for that case too.
For this to work you simply need to download the NSDictionary category from this URL: https://github.com/nicklockwood/XMLDictionary
.h
#import <Foundation/Foundation.h>
#interface JMAmazonProcessor : NSObject
+(NSArray*)processAmazonResponseWithXMLData:(NSData*)responseObject;
#end
and for
.m
#import "JMAmazonProcessor.h"
#implementation JMAmazonProcessor
+(NSString*)getBookTitleWithArray:(NSArray*)array{
return [[array[0] objectForKey:kAmazonAHREFKey] objectForKey:kAmazonUnderscoreTextKey];
}
+(NSString*)getBookAuthorWithArray:(NSArray*)array{
id bookAuthor = [[array[1] objectForKey:kAmazonAHREFKey] objectForKey:kAmazonUnderscoreTextKey];
if(!bookAuthor){
bookAuthor = [array[1] objectForKey:kAmazonUnderscoreTextKey];
}
if([bookAuthor isKindOfClass:[NSArray class]]){
bookAuthor = [bookAuthor componentsJoinedByString:#" "];
}
return bookAuthor;
}
+(NSString*)getPriceFromDictionary:(NSDictionary*)dictionary{
return [NSString stringWithUTF8String:[[[[dictionary objectForKey:#"font"] lastObject] objectForKey:#"b"] cStringUsingEncoding:NSUTF8StringEncoding]];
}
+(NSString*)getRatingWithCurrentRatingDictionary:(NSDictionary*)ratingDictionary{
NSString * stars;
if([ratingDictionary objectForKey:#"_src"]){
NSString * possibleStarsURL = [ratingDictionary objectForKey:#"_src"];
if([possibleStarsURL rangeOfString:#"stars-" options:NSCaseInsensitiveSearch].location != NSNotFound){
stars = [[[[[possibleStarsURL componentsSeparatedByString:#"stars-"] lastObject] componentsSeparatedByString:#"."] firstObject] stringByReplacingOccurrencesOfString:#"-" withString:#"."];
}
}
return stars;
}
+(NSString*)getRatingFromDictionary:(NSDictionary*)dictionary{
id currentDictionary = [dictionary objectForKey:#"img"];
NSString *rating;
if([currentDictionary isKindOfClass:[NSArray class]]){
for(int i = 0; i < [currentDictionary count]; i++){
NSDictionary *currentRatingDictionary = [currentDictionary objectAtIndex:i];
if((rating = [self getRatingWithCurrentRatingDictionary:currentRatingDictionary])){
break;
}
}
}
else if([currentDictionary isKindOfClass:[NSDictionary class]]){
rating = [self getRatingWithCurrentRatingDictionary:currentDictionary];
}
if(!rating) rating = #"Rating is not currently available";
return rating;
}
+(NSArray*)processAmazonResponseWithXMLData:(NSData*)responseObject{
NSMutableArray *bookEntries = [[NSMutableArray alloc] init];
NSDictionary * itemDictionary = [[NSDictionary dictionaryWithXMLData:responseObject] objectForKey:kAmazonRootNode];
for(int i = 0; i < [[itemDictionary objectForKey:kAmazonFeedItemKey] count]; i++){
RSSBookEntryModel *cBEO = [[RSSBookEntryModel alloc] init];
NSDictionary *currentItem = [[itemDictionary objectForKey:kAmazonFeedItemKey] objectAtIndex:i];
NSString *finalXMLString = [NSString stringWithFormat:#"%#%#%#", kAmazonStartTag, [currentItem objectForKey:kAmazonDescriptionKey], kAmazonEndTag];
NSDictionary *cData = [NSDictionary dictionaryWithXMLString:finalXMLString];
NSArray *bookDetailsDictionary = [cData objectForKey:kAmazonSpanKey];
NSString *bIOURL = [[[[cData objectForKey:#"div"] objectForKey:kAmazonAHREFKey] objectForKey:#"img"] objectForKey:#"_src"];
NSString *bookImageCoverID = [[[[bIOURL componentsSeparatedByString:kAmazonBookCoverBaseURL] lastObject] componentsSeparatedByString:#"."] firstObject];
cBEO.bookTitle = [self getBookTitleWithArray:bookDetailsDictionary];
cBEO.bookAuthor = [self getBookAuthorWithArray:bookDetailsDictionary];
cBEO.bookCoverImageThumbnailURL = [NSString stringWithFormat:#"%#%#%#%#", kAmazonBookCoverBaseURL, bookImageCoverID, kAmazonBookCoverThumbnailSize, kAmazonBookCoverFileExtention];
cBEO.bookCoverImageOriginalURL = [NSString stringWithFormat:#"%#%#%#%#", kAmazonBookCoverBaseURL, bookImageCoverID, kAmazonBookCoverMaxSize, kAmazonBookCoverFileExtention];
cBEO.bookPrice = [self getPriceFromDictionary:cData];
cBEO.bookRating = [self getRatingFromDictionary:cData];
[bookEntries addObject:cBEO];
}
return bookEntries;
}
#end
Sorry.
Here it is:
This is the object model you want to use, its pretty straight forward.
#interface RSSBookEntryModel : NSObject
#property (strong, nonatomic) NSString *bookTitle;
#property (strong, nonatomic) NSString *bookAuthor;
#property (strong, nonatomic) NSString *bookCoverImageThumbnailURL;
#property (strong, nonatomic) NSString *bookCoverImageOriginalURL;
#property (strong, nonatomic) NSData *bookCoverThumbnailImage;
#property (strong, nonatomic) NSData *bookCoverOriginalImage;
#property (strong, nonatomic) NSString *bookPrice;
#property (strong, nonatomic) NSString *bookRating;
-(NSString*)description;
#end
And here are the constants I'm using to keep everything clean.
Constant.h
extern NSString * const kAmazonRootNode;
extern NSString * const kAmazonStartTag;
extern NSString * const kAmazonEndTag;
extern NSString * const kAmazonFeedItemKey;
extern NSString *const kAmazonSpanKey;
extern NSString * const kAmazonDescriptionKey;
extern NSString *const kAmazonUnderscoreTextKey;
extern NSString *const kAmazonAHREFKey;
extern NSString *const kAmazonBookCoverBaseURL;
extern NSString *const kAmazonBookCoverThumbnailSize;
extern NSString *const kAmazonBookCoverMaxSize;
extern NSString *const kAmazonBookCoverFileExtention;
And here's the Constants.m file.
NSString * const kAmazonRootNode = #"channel";
NSString * const kAmazonStartTag = #"<startTag>";
NSString * const kAmazonEndTag = #"</startTag>";
NSString * const kAmazonFeedItemKey = #"item";
NSString *const kAmazonSpanKey = #"span";
NSString * const kAmazonDescriptionKey = #"description";
NSString *const kAmazonUnderscoreTextKey = #"__text";
NSString *const kAmazonAHREFKey = #"a";
NSString *const kAmazonBookCoverBaseURL = #"http://ecx.images-amazon.com/images/";
NSString *const kAmazonBookCoverThumbnailSize = #"._SL100";
NSString *const kAmazonBookCoverMaxSize = #"._SL500";
NSString *const kAmazonBookCoverFileExtention = #".jpg";

This is a pretty weak alternative here, but maybe it helps somehow:
//title
console.log("TITLE: " + $(".riRssTitle").text().trim());
//image
console.log("IMAGE: " + $(document).find("img").attr("src"));
//author
console.log("AUTHOR: " + $(".riRssContributor").find("a").text().trim());
//new price and striked price
var new_price_striked_element = $("a:contains('Buy new')").siblings("strike");
if(new_price_striked_element){
console.log("NEW PRICE STRIKED: " + new_price_striked_element.text().trim());
}else{
console.log("NEW PRICE: " + $("a:contains('Buy new')").siblings("b").text().trim());
}
//used price
console.log("USED PRICE FROM: " + $(".price").text().trim());
//stars
var url = $("img[src*='stars']").attr("src");
var myRegexp = /stars-([0-9]-[0-9])/g;
var match = myRegexp.exec(url);
console.log("STARS: " + match[1]);
EXAMPLE:http://jsfiddle.net/qpuaxtv3/

Related

json photo path format in xcode

i have a jpg file in my database,
how can i used json/php build in my Xcode project?
my jpg link in php format like this:
[{"photo_path":"photo_path.jpg,"title":"test topic""]}
i know when i build "title" part,i can use NSString format,
but in "photo_path.jpg" part,did i use NSString also??
#property (nonatomic, strong) NSString * title;
#property (nonatomic, strong) NSString * photo_path;
#property (strong, nonatomic) IBOutlet UITextView *detaillabel;
#property (strong, nonatomic) IBOutlet UIImageView *photolabel;
and here is my json.m part:
- (void) retrieveData
{
NSURL * url = [NSURL URLWithString:getDataURL];
NSData * data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
HomeArray = [[NSMutableArray alloc]init];
for (int i = 0; i < json.count; i++)
{
NSString * titletopic = [[json objectAtIndex:i] objectForKey:#"title"];
NSString * detailinfo = [[json objectAtIndex:i] objectForKey:#"detail"];
NSString * photo = [[json objectAtIndex:i] objectForKey:#"photo_path"];
NSString * dateinfo = [[json objectAtIndex:i] objectForKey:#"date"];
HomeDetail * home2 = [[HomeDetail alloc]initWithTitle:titletopic
andDetail:detailinfo
andPhoto_path:photo
andDate:dateinfo];
[HomeArray addObject:home2];
}
[self.myTableView reloadData];
}
You need to store the path/url of your image in your database. By path I mean local path (if the image is stored locally) or URL if it's somewhere on the interwebz.
Fetch that URL whichever way pleases you (JSON is fine), and make your way through the JSON to retrieve the NSString of that URL.
( you appear to have that all done already, in your NSString *photo
Though i suggest you rename "photo" with photoPath or something more clear because the photo name strongly suggests it's already an image, which it isn't yet :)
Then simply apply this where you need the UIImage object:
NSURL *url = [NSURL URLWithString:photo];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data cache:NO];
You can then add it to an imageview using setImage: or .image

Can't get data on detailviewcontroller with Hpple parsing

I am a beginner in Obj-C and I try to make an app with this raywenderlich tutorial.
I parse html page with Title of articles (mininglife.ru) , also I getting an urls of each articles and keep it in an NSMutableArray for using it in my DetailviewController.
But when I try to pull urls off and put it in NSUrl nothing happens. I've tried a lot of ways, Can you help me with it and try to explain if I do something wrong. Thank you.
-(void)loadArticles{
Articlelist *urlOfArticle = [_objects objectAtIndex:self]; // from previous parsing
NSURL *articleUrl = [NSURL URLWithString:urlOfArticle.url];// I think this string is wrong, or?
NSData *htmlUrlsData = [NSData dataWithContentsOfURL:articleUrl];
TFHpple *articleParser = [TFHpple hppleWithHTMLData:htmlUrlsData];
NSString *articleNameXpath = #"/html/body/div[1]/div/div[1]/main/article/h1";
// NSString *articleContentXpath = #"//div[#class'entry-content']//p";
NSArray *articleNameNodes = [articleParser searchWithXPathQuery:articleNameXpath];
// NSArray *articleContentNodes = [articleParser searchWithXPathQuery:articleContentXpath];
NSMutableArray *newArticleArray = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in articleNameNodes) {
Article *newArticleName = [[Article alloc] init];
[newArticleArray addObject:newArticleName];
newArticleName.name = [[element firstChild] content];
}
_articleName = newArticleArray;
[self.tableView reloadData];
}
Change interface to this
#interface MasterViewController () {
NSMutableArray *_articles;
}
#end
Add this to MasterViewController
- (void)loadArticles
{
NSURL *articlesUrl = [NSURL URLWithString:#"http://mininglife.ru"];
NSData *articlesHtmlData = [NSData dataWithContentsOfURL:articlesUrl];
TFHpple *articlesParser = [TFHpple hppleWithHTMLData:articlesHtmlData];
NSString *articlesXpathQueryString = #"/html/body/div[1]/div/div[1]/main/article/h1";
NSArray *articlesNodes = [articlesParser searchWithXPathQuery:articlesXpathQueryString];
NSMutableArray *newArticles = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in articlesNodes) {
Article *article = [[Article alloc] init];
[newArticles addObject:article];
article.title = [[element firstChild] content];
article.url = [element objectForKey:#"href"];
}
_articles = newArticles;
[self.tableView reloadData];
}
Change DetailviewController.h's interface to
#class Article;
#interface DetailViewController : UIViewController
#property (strong, nonatomic) Article *article;
#property (strong, nonatomic) IBOutlet UILabel *detailDescriptionLabel;
#end
Change DetailViewController.m to
#import "DetailViewController.h"
#import "Article.h"
#import "TFHpple.h"
#implementation DetailViewController
#synthesize detailDescriptionLabel = _detailDescriptionLabel;
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadArticle];
}
- (void)loadArticle
{
NSURL *articleUrl = [NSURL URLWithString:self.article.url];
NSData *articleHtmlData = [NSData dataWithContentsOfURL:articleUrl];
TFHpple *articleParser = [TFHpple hppleWithHTMLData:articleHtmlData];
NSString *articleXpathQueryString = #"//div[#class'entry-content']//p";
NSArray *articleNodes = [articleParser searchWithXPathQuery:articleXpathQueryString];
NSMutableArray *newArticleContents = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in articleNodes) {
[newArticleContents addObject:[[element firstChild] content]];
}
NSLog(#"%#", newArticleContents);
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"Detail", #"Detail");
}
return self;
}
#end
Don't forget to change all call to loadTutorials to loadArticles in MasterViewController. PS: This example only prints the articles content to the console
Your xPath might be wrong as well

How to put JSON element into UITextView?

I have a MySQL database and a PHP script that work perfectly. However, I was wondering how I could get this data from JSON format to a UITextView. I also have a table being populated with 2 other JSON elements. Thanks!
TableInfo.h
#import <Foundation/Foundation.h>
#interface TableInfo : NSObject
#property (nonatomic, strong) NSString *Title;
#property (nonatomic, strong) NSString *SubTitle;
#property (nonatomic, strong) NSString *Description;
#end
HomeModel.h
#import <Foundation/Foundation.h>
#protocol HomeModelProtocol <NSObject>
- (void)itemsDownloaded:(NSArray *)items;
#end
#interface HomeModel : NSObject <NSURLConnectionDataDelegate>
#property (nonatomic, weak) id<HomeModelProtocol> delegate;
- (void)downloadItems;
#end
HomeModel.m
#import "HomeModel.h"
#import "TableInfo.h"
#interface HomeModel()
{
NSMutableData *_downloadedData;
}
#end
#implementation HomeModel
- (void)downloadItems
{
// Download the json file
NSURL *jsonFileUrl = [NSURL URLWithString:#"http://gandouhaiti.ueuo.com/service.php"];
NSLog(#"Donwload the JSON file");
// Create the request
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileUrl];
NSLog(#"Create the request");
// Create the NSURLConnection
[NSURLConnection connectionWithRequest:urlRequest delegate:self];
NSLog(#"Create the NSURLConnection");
}
#pragma mark NSURLConnectionDataProtocol Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"Inititalize the data object");
// Initialize the data object
_downloadedData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the newly downloaded data
[_downloadedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// Create an array to store the locations
NSMutableArray *_locations = [[NSMutableArray alloc] init];
// Parse the JSON that came in
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:_downloadedData options:NSJSONReadingAllowFragments error:&error];
// Loop through Json objects, create question objects and add them to our questions array
for (int i = 0; i < jsonArray.count; i++)
{
NSDictionary *jsonElement = jsonArray[i];
// Create a new location object and set its props to JsonElement properties
TableInfo *newdata = [[TableInfo alloc] init];
newdata.Title = jsonElement[#"Title"];
newdata.SubTitle = jsonElement[#"SubTitle"];
newdata.description = jsonElement[#"Description"];
// Add this question to the locations array
[_locations addObject:newdata];
}
// Ready to notify delegate that data is ready and pass back items
if (self.delegate)
{
[self.delegate itemsDownloaded:_locations];
}
}
#end
If you wan to display the JSON in UITextView in storyboard, kindly try the following:
#implementation ViewController
NSString * JSON;
-(void) viewDidLoad
{
JSON = //get data from remote;
NSString *stringForTextView = #"";
NSData *data = [JSON dataUsingEncoding:NSUTF8StringEncoding];
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
if([array count] >0)
{
for(NSDictionary *d in array)
{
stringForTextView = [NSString stringWithFormat:#"Title:%#\nSubTitle:%#\nDescription:%#\n", [d valueForKey:#"Title"], [d valueForKey:#"SubTitle"], [d valueForKey:#"Description"]];
}
}
_textView.text = stringForTextView;
}
#end

IOS Regular parse HTML

i want to parse html content into Dictionary
EDIT:
I need to parse just simple HTML, don't need to consider the complex situation.
WEB side: when I was in the system input information, using the HTML editor. But fix the old WEB system , need to modify the place more, so temporary use parsing HTML mode in the current version of the APP。
END:
Html just like this:
<p>hahaha</p><img src="aaaa.jpg"/>heihei<img src="bbb.jpg"/>guagua
i want the result is:
text hahaha
img aaaa.jpg
text heihei
img bbb.jpg
text guagua
my code is:
//<p>hahaha</p><img src="aaaa.jpg"/>heihei<img src="bbb.jpg"/>guagua
//for this
//NSArray = {0,1,2,3,4}
//NSDictionary{Sort-Key,V}={{0,{text,hahaha}},{1,{img,aaaa.jpg}},{2,{text,heihei}},{3, {img,bbb.jpg}},{4,{text,guagua}}}
-(NSArray*)RegularExpression:(NSString *)str dic:(NSMutableDictionary**)dic
{
if(str == nil) return nil;
NSString *pgnText = str;
NSString* tags=#"<[p|div].*?>(.*?)</[p|div].*?>";
NSString *regTags = tags;
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *matches = [regex matchesInString:pgnText
options:0
range:NSMakeRange(0, [pgnText length])];
NSMutableArray* arrItems = [[NSMutableArray alloc] initWithCapacity:[matches count]];
if(matches.count >0){
for (NSTextCheckingResult *match in matches) {
NSString *tagValue = [pgnText substringWithRange:[match rangeAtIndex:1]];
NSArray* arr = [self RegularExpression:tagValue dic:dic];
[arrItems addObjectsFromArray:arr];
}
}
else{
NSString* regTags2 = #".*?<img.*?src.*?=.*?[\"|”](.*?)[\"|”].*?/>";
NSRegularExpression *regex2 = [NSRegularExpression regularExpressionWithPattern:regTags2 options:NSRegularExpressionCaseInsensitive|NSRegularExpressionAnchorsMatchLines error:&error];
pgnText = str;
NSArray *matches2 = [regex2 matchesInString:pgnText
options:0
range:NSMakeRange(0, [pgnText length])];
for (NSTextCheckingResult *match in matches2) {
NSString *tagValue = [pgnText substringWithRange:[match rangeAtIndex:1]];
NSLog(#"%#",tagValue);
}
}
return [arrItems autorelease];
}
Who has done similar function?
Keys in a dictionary must be unique. You cannot have more than one "img" key.
Check out this SO question: Objective-C DOM XML parser for iPhone

I want to get like ™ character in db. how? in ios

in mysql db table
varchar title(20) - db table column.
title: Banana™ - table row.
in return.php (server)
$get_query=$_GET['query'];
$connect=mysql_connect("localhost","root","") or die("die");
mysql_select_db("testdb",$connect);
$query=mysql_query($get_query,$connect);
while($row = mysql_fetch_array($query ))
{
$list[]=$row;
}
print json_encode($list);
mysql_free_result($query);
mysql_close($connect);
in ios (client)
NSString * szURL =[NSString stringWithFormat:#"http://localhost/return.php?query=%#",query];
NSURL *url = [NSURL URLWithString:[szURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding ]];
NSString *strData = [NSString stringWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:&error];
NSDictionary *rootItem = (NSDictionary *)[strData JSONValue];
NSArray * appLists= (NSArray *)rootItem;
NSMutableArray *resultArray =[[[NSMutableArray alloc]init] autorelease];
for(NSDictionary * oneApp in appLists)
{
NSString *appTitle=(NSString*)[oneApp objectForKey:#"title"];
}
but appTitle is NULL;
I think , I need to covert character.
™ is problem.
How I get Banana™ by (NSString *)??
Maybe the problem is here:
NSDictionary *rootItem = (NSDictionary *)[strData JSONValue];
NSArray * appLists= (NSArray *)rootItem;
Is it an Array or a Dictionary? Check this out before iterate over appLists. A NSLog to [strData JSONValue]; can be really useful.