我想知道你是否可以将html标签变成数组。
<title>aa</title>
<link>http://dailynews.yahoo.co.jp/fc/domestic/nuke_disaster_prevention/?id=6170385</link>
<pubDate>Wed, 12 Aug 2015 17:14:19 +0900</pubDate>
<guid isPermaLink="false">yahoo/news/topics/6170385</guid>
</item>
<item>
<title>bb</title>
<link>http://dailynews.yahoo.co.jp/fc/local/okinawa_us_armed_forces/?id=6170398</link>
<pubDate>Wed, 12 Aug 2015 17:57:37 +0900</pubDate>
<enclosure length="133" url="http://i.yimg.jp/images/icon/photo.gif" type="image/gif">
</enclosure>
<guid isPermaLink="false">yahoo/news/topics/6170398</guid>
</item>
我有这些html标签,我想通过标签(按标题,链接,描述等)将其转换为数组 是否可能,因为我希望它是一个数组,所以我可以将它插入我的数据库表。
答案 0 :(得分:0)
您可以使用以下示例来完成此操作。然后将字符串转换为数组
<?php
$myhtml = <<<EOF
?>
<html>
<head>
<title>My Page</title>
</head>
<body>
<p><a href="/mypage1">Hello World!</a></p>
<p><a href="/mypage2">Another Hello World!</a></p>
</body>
</html><?php
EOF;
$doc = new DOMDocument();
$doc->loadHTML($myhtml);
$tags = $doc->getElementsByTagName('a');
foreach ($tags as $tag) {
echo $tag->getAttribute('href').' | '.$tag->nodeValue."\n";
}
?>
答案 1 :(得分:0)
您的内容看起来像XML?您可以使用simplexml_load_string()
将XML字符串解释为对象:
<?php
$mytext ='
<items>
<item>
<title>aa</title>
<link>http://dailynews.yahoo.co.jp/fc/domestic/nuke_disaster_prevention/?id=6170385</link>
<pubDate>Wed, 12 Aug 2015 17:14:19 +0900</pubDate>
<guid isPermaLink="false">yahoo/news/topics/6170385</guid>
</item>
<item>
<title>bb</title>
<link>http://dailynews.yahoo.co.jp/fc/local/okinawa_us_armed_forces/?id=6170398</link>
<pubDate>Wed, 12 Aug 2015 17:57:37 +0900</pubDate>
<enclosure length="133" url="http://i.yimg.jp/images/icon/photo.gif" type="image/gif">
</enclosure>
<guid isPermaLink="false">yahoo/news/topics/6170398</guid>
</item>
</items>';
$xml = simplexml_load_string($mytext);
print_r($xml);
?>
<强>输出强>:
SimpleXMLElement Object
(
[item] => Array
(
[0] => SimpleXMLElement Object
(
[title] => aa
[link] => http://dailynews.yahoo.co.jp/fc/domestic/nuke_disaster_prevention/?id=6170385
[pubDate] => Wed, 12 Aug 2015 17:14:19 +0900
[guid] => yahoo/news/topics/6170385
)
[1] => SimpleXMLElement Object
(
[title] => bb
[link] => http://dailynews.yahoo.co.jp/fc/local/okinawa_us_armed_forces/?id=6170398
[pubDate] => Wed, 12 Aug 2015 17:57:37 +0900
[enclosure] => SimpleXMLElement Object
(
[@attributes] => Array
(
[length] => 133
[url] => http://i.yimg.jp/images/icon/photo.gif
[type] => image/gif
)
)
[guid] => yahoo/news/topics/6170398
)
)
)
遍历对象并将值插入数据库
foreach($xml as $item) {
//Insert into database
echo $item->title;
echo $item->link;
}