我有一个 php 变量,其中包含一个 html 文档。我正在尝试将 li>span 和 li>strong 提取到某种关联数组中。
$html 变量中的 html 为
<ul class="ul-data" xmlns:utils="urn:utils" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<li><span>
Vehicle make
</span><strong>CITROEN</strong></li>
<li><span>
Year of manufacture
</span><strong>1997</strong></li>
<li><span>
Cylinder capacity (cc)
</span><strong>1124cc
</strong></li>
<li><span>
Fuel type
</span><strong>PETROL</strong></li>
<li><span>
Vehicle colour
</span><strong>BLUE</strong></li>
<li><span>
Vehicle type approval
</span><strong>
Not available
</strong></li>
</ul>
以及我到目前为止的代码
$dom = new DOMDocument();
//as @Larry.Z comments, you forgot to load the $html
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
//assuming there can be more than one "result set" on each page
$results = array();
$result_divs = $xpath->query('//ul[@class="ul-data"]');
foreach ($result_divs as $result_div) {
$result=array();
foreach ($result_div->childNodes as $result_item) {
$content=trim($result_item->textContent);
if ($content!='') $result[]=$content;
}
$results[]=$result;
}
echo '<pre>';
print_r($results);
echo '</pre>';
打印出来
Array
(
[0] => Array
(
[0] => Vehicle make
CITROEN
[1] => Date of first registration
27 August 1997
[2] => Year of manufacture
1997
[3] => Cylinder capacity (cc)
1124cc
[4] => Fuel type
PETROL
[5] => Vehicle colour
BLUE
[6] => Vehicle type approval
Not available
)
)
如何让它设置像这样的关联数组
[Vehicle make] => CITREON
问题是我需要获取 li> span 作为键,然后获取 <strong>
之间的数据作为值。
最佳答案
由于您的 html 只有一个 ul,因此不需要外部循环。
您可以抓取所有 li
标签,并访问第一个和第二个子元素:
$dom = new DOMDocument();
$dom->loadHTML($html);
$results = array();
foreach ($dom->getElementsByTagName('li') as $li) {
$results[$li->childNodes->item(0)->textContent]=$li->childNodes->item(1)->textContent;
}
print_r($results);
关于php - 如何提取 HTML 并将其放入 php 关联数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33942595/