php - 如何提取 HTML 并将其放入 php 关联数组中?

标签 php html parsing xpath

我有一个 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/

相关文章:

Javascript if else 改变 css

Android解析xml和AsyncTask doInBackground方法永远不会完成

c - 一旦词法分析器返回一个标记,如何开始解析? (构建编译器)

php - 如何获取很久以前提出的查询的 ID 并将其发布到另一个表?

javascript - jQuery Ajax 从网站的另一个页面加载内容

php - 将 OAuth 2.0 与自定义 API 集成的概述(用 Laravel 编写)

javascript - Javascript 动态编辑页面内容

csv - HIVE - 手动解析数据,用双引号括起来,用逗号分隔

php - 安装后 Shopware Slim 应用程序错误

php - 在 PHP 中使用 cURL 的 SSL Twitter oauth