根据< div>的内容创建数组PHP中的标签 [英] Create array from the contents of <div> tags in php
问题描述
我已将网页内容分配给变量 $ html
I have the contents of a web page assigned to a variable $html
以下是示例 $ html
的内容:
<div class="content">something here</div>
<span>something random thrown in <strong>here</strong></span>
<div class="content">more stuff</div>
如何使用PHP创建一个数组来查找< div class = content>< / div>
这样的区域(对于上述示例),因此:
How, using PHP can I create an array from that that finds the contents of <div class="content"></div>
regions like this (for the example above) so:
echo $array[0] . "\n" . $array[1]; //etc
输出
something here
more stuff
推荐答案
假设这只是OP中的简化案例,而实际情况更为复杂,则需要使用XPath。
Assuming this is just a simplified case in the OP and the real situation is more complicated, you'll want to use XPath.
如果它确实很复杂,那么您可能要使用 DOMDocument (与 DOMXPath ),但这是一个使用SimpleXML的简单示例
If it's really complex, then you may want to use DOMDocument (with DOMXPath), but here's a simple example using SimpleXML
$xml = new SimpleXMLElement($html);
$result = $xml->xpath('//div[@class="content"]');
while(list( , $node) = each($result)) {
echo $node,"\n";
}
由于您明确询问要为此创建数组,因此可以使用:
Since you explicitly asked about creating an array for this, you could use:
$res_Arr = array();
while(list( , $node) = each($result)) {
$res_Arr[] = $node;
}
和 $ res_Arr
将是包含您要查找的内容的数组。
and $res_Arr
would be an array with the contents you're looking for.
请参见 http://php.net/manual/en/simplexmlelement.xpath.php 用于php SimpleXML Xpath信息和 http://www.w3.org/TR/xpath 了解XPath规范
See http://php.net/manual/en/simplexmlelement.xpath.php for php SimpleXML Xpath info and http://www.w3.org/TR/xpath for the XPath specifications
这篇关于根据< div>的内容创建数组PHP中的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!