我正在使用WordPress rest API开发应用程序。在WordPress rest API post中,有一个名为content的属性,该属性具有进一步的属性,如Json所示。在rendered属性中有一个html标签。我只想从那里过滤img标签。如何在Dart或php中实现此目的?
"id": 1660,
"link": "http://localhost/soledesign/bill-baber/",
"title": {
"rendered": "Bill Baber"
},
"content": {
"rendered": "<h2>Bill Baber Knitwear opened our doors for the first time back in 1977 and have been producing the finest Scottish knitwear ever since.</h2>\n<p>Helen & Bill Baber design and produce the whole collection themselves, with a little help from time to time. The collection includes mostly ladies wear, with some unisex styles, sorry guys! You’ll find full length silk jackets, luxuriously soft cashmere shawls, lightweight linen tops and stunning accessories to pep up any outfit. The widest selection can be found in store at <a href=\"https://billbaber.com/contact-us/\">66 Grassmarket</a>, however we do have a collection available <a href=\"https://billbaber.com/shop/\">online</a> for you to enjoy and we even supply other <a href=\"https://billbaber.com/stockists/\">retailers</a> all over the world!</p>\n<p>On this site you will see garments that we carry in stock or produce to order. in some cases we may hold a little stock ready to go, but generally each items is made from scratch when you order it. In store we have a boutique collection many of which simply cannot be reproduced, sometimes the yarn has run out or the style was a one off creation.</p>\n<p> </p>\n<p><img src=\"https://billbaber.com/wp-content/uploads/2019/09/crail_silver-190x285.jpg\" alt=\"Crail Top\" /><img src=\"https://billbaber.com/wp-content/uploads/2019/09/liscannor_crew-190x285.jpg\" alt=\"Crew Jumper\" /><img src=\"https://billbaber.com/wp-content/uploads/2017/09/t_alt_dne-190x285.jpg\" alt=\"Alto Top\" /><img src=\"https://billbaber.com/wp-content/uploads/2017/09/t_dtt_sge-190x285.jpg\" alt=\"Dot\" /></p>\n<p> </p>\n",
"protected": false
},
"excerpt": {
"rendered": "<p>Bill Baber Knitwear opened our doors for the first time back in 1977 and have been producing the finest Scottish knitwear ever since. Helen & Bill Baber design and produce the whole collection themselves, with a little help from time to time. The collection includes mostly ladies wear, with some unisex styles, sorry guys! You’ll […]</p>\n",
"protected": false
},
"author": 83
},
您可以在下面复制粘贴运行完整的代码。
您可以使用包https://pub.dev/packages/html。
步骤1:删除特殊字符并解析json字符串,可以看到Payload
完整代码中的类
String result = jsonString.replaceAll("\n", "");
Payload payload = payloadFromJson(result);
第2步:DOM Element
用querySelectorAll("img")
import 'package:html/parser.dart' show parse;
import 'package:html/dom.dart' as dom;
...
var document = parse(payload.content.rendered);
var imgList = document.querySelectorAll("img");
for (dom.Element img in imgList) {
print(img.attributes["src"]);
print(img.toString());
}
输出
I/flutter (11892): https://billbaber.com/wp-content/uploads/2019/09/crail_silver-190x285.jpg
I/flutter (11892): https://billbaber.com/wp-content/uploads/2019/09/liscannor_crew-190x285.jpg
I/flutter (11892): https://billbaber.com/wp-content/uploads/2017/09/t_alt_dne-190x285.jpg
I/flutter (11892): https://billbaber.com/wp-content/uploads/2017/09/t_dtt_sge-190x285.jpg
工作演示
完整的代码
import 'package:flutter/material.dart';
import 'package:html/parser.dart' show parse;
import 'package:html/dom.dart' as dom;
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
int id;
String link;
Title title;
Content content;
Content excerpt;
int author;
Payload({
this.id,
this.link,
this.title,
this.content,
this.excerpt,
this.author,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
id: json["id"],
link: json["link"],
title: Title.fromJson(json["title"]),
content: Content.fromJson(json["content"]),
excerpt: Content.fromJson(json["excerpt"]),
author: json["author"],
);
Map<String, dynamic> toJson() => {
"id": id,
"link": link,
"title": title.toJson(),
"content": content.toJson(),
"excerpt": excerpt.toJson(),
"author": author,
};
}
class Content {
String rendered;
bool protected;
Content({
this.rendered,
this.protected,
});
factory Content.fromJson(Map<String, dynamic> json) => Content(
rendered: json["rendered"],
protected: json["protected"],
);
Map<String, dynamic> toJson() => {
"rendered": rendered,
"protected": protected,
};
}
class Title {
String rendered;
Title({
this.rendered,
});
factory Title.fromJson(Map<String, dynamic> json) => Title(
rendered: json["rendered"],
);
Map<String, dynamic> toJson() => {
"rendered": rendered,
};
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future<List<String>> _future;
Future<List<String>> _getData() {
String jsonString = r'''
{
"id": 1660,
"link": "http://localhost/soledesign/bill-baber/",
"title": {
"rendered": "Bill Baber"
},
"content": {
"rendered": "<h2>Bill Baber Knitwear opened our doors for the first time back in 1977 and have been producing the finest Scottish knitwear ever since.</h2>\n<p>Helen & Bill Baber design and produce the whole collection themselves, with a little help from time to time. The collection includes mostly ladies wear, with some unisex styles, sorry guys! You’ll find full length silk jackets, luxuriously soft cashmere shawls, lightweight linen tops and stunning accessories to pep up any outfit. The widest selection can be found in store at <a href=\"https://billbaber.com/contact-us/\">66 Grassmarket</a>, however we do have a collection available <a href=\"https://billbaber.com/shop/\">online</a> for you to enjoy and we even supply other <a href=\"https://billbaber.com/stockists/\">retailers</a> all over the world!</p>\n<p>On this site you will see garments that we carry in stock or produce to order. in some cases we may hold a little stock ready to go, but generally each items is made from scratch when you order it. In store we have a boutique collection many of which simply cannot be reproduced, sometimes the yarn has run out or the style was a one off creation.</p>\n<p> </p>\n<p><img src=\"https://billbaber.com/wp-content/uploads/2019/09/crail_silver-190x285.jpg\" alt=\"Crail Top\" /><img src=\"https://billbaber.com/wp-content/uploads/2019/09/liscannor_crew-190x285.jpg\" alt=\"Crew Jumper\" /><img src=\"https://billbaber.com/wp-content/uploads/2017/09/t_alt_dne-190x285.jpg\" alt=\"Alto Top\" /><img src=\"https://billbaber.com/wp-content/uploads/2017/09/t_dtt_sge-190x285.jpg\" alt=\"Dot\" /></p>\n<p> </p>\n",
"protected": false
},
"excerpt": {
"rendered": "<p>Bill Baber Knitwear opened our doors for the first time back in 1977 and have been producing the finest Scottish knitwear ever since. Helen & Bill Baber design and produce the whole collection themselves, with a little help from time to time. The collection includes mostly ladies wear, with some unisex styles, sorry guys! You’ll […]</p>\n",
"protected": false
},
"author": 83
}
''';
String result = jsonString.replaceAll("\n", "");
Payload payload = payloadFromJson(result);
var document = parse(payload.content.rendered);
var imgList = document.querySelectorAll("img");
List<String> imageList = [];
for (dom.Element img in imgList) {
print(img.attributes["src"]);
imageList.add(img.attributes["src"]);
}
return Future.value(imageList);
}
@override
void initState() {
_future = _getData();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder<List<String>>(
future: _getData(),
builder: (BuildContext context, AsyncSnapshot<List<String>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('Input a URL to start');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return ListView.builder(
itemCount:
snapshot.data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(snapshot.data[index]),
);
});
}
}
}));
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句