首页 > 解决方案 > 我可以将 domxpath 嵌套类的结果放入带有键 => 值的数组中吗?

问题描述

我从网页中为客户获取一些数据并且效果很好,它通过将 \n 分解为新行来获取单独的行中的所有数据,然后我将这些数据映射到特定的数组数据以填充表单字段。对于每个需要的值,就像这样:

$lines = explode("\n", $html);
$data['vraagprijs']         = preg_replace("/[^0-9]/", "", $lines[5]);

但是,我需要的数据今天可能在第 10 行,但明天很可能在第 11 行。所以我想将这些值放入命名数组中。URL 上的 HTML 示例如下:

<div class="item_list">             
<span class="item first status">
    <span class="itemName">Status</span>                        
    <span class="itemValue">Sold</span>
</span>
<span class="item price">
    <span class="itemName">Vraagprijs</span>
    <span class="itemValue">389.000</span>
</span>
<span class="item condition">
    <span class="itemName">Aanvaarding</span>
    <span class="itemValue">In overleg</span>
</span>
...
</div>

这是我的功能模型:

$tagName3   = 'div';
$attrName3  = 'class';
$attrValue3 = 'item_list';
$html       = getShortTags($tagName3, $attrName3, $attrValue3, $url); 

function getShortTags($tagName, $attrName, $attrValue, $url = "", $exclAttrValue = 'itemTitle') {

    $dom = $this->getDom($url);

    $html                 = '';
    $domxpath             = new \DOMXPath($dom);
    $newDom               = new \DOMDocument;
    $newDom->formatOutput = true;

    $filtered = $domxpath->query(" //" . $tagName . "[@" . $attrName . "='" . $attrValue . "']/descendant::text()[not(parent::span/@" . $attrName . "='" . $exclAttrValue . "')] ");
    $i        = 0;
    while ($myItem   = $filtered->item($i++)) {
        $node   = $newDom->importNode($myItem, true);
        $newDom->appendChild($node); 
    }
    $html = $newDom->saveHTML();
    return $html;
}

我得到了什么?

Status\nSold\nVraagprijs\n389.000\nIn overleg\n....

所需的输出如下:

$html = array("Status" => "Sold", "Vraagprijs" => "389.000", "Aanvaarding" => "In overleg", ...)

有没有办法“循环”通过 itemList 并将每个 itemName 和 itemValue 放入关联数组中?

标签: phpxmldomxpath

解决方案


如果您对该方法的作用感到满意getShortTags()(或者如果它在其他地方使用并且很难调整),那么您可以处理返回值。

此代码首先用于explode()按行拆分输出,使用array_map()trim()删除任何空格等,然后将结果传递array_filter()给删除空行。这将成对保留数据,因此一种简单的方法是使用array_chunk()提取对,然后foreach()使用第一个作为键,第二个作为值的对...

$html = getShortTags($tagName3, $attrName3, $attrValue3, $url);
$lines = array_filter(array_map("trim", explode(PHP_EOL, $html)));
$pairs = array_chunk($lines, 2);
$output = [];
foreach ( $pairs as $pair ) {
    $output[$pair[0]] = $pair[1];
}
print_r($output);

与样本数据给出..

Array
(
    [Status] => Sold
    [Vraagprijs] => 389.000
    [Aanvaarding] => In overleg
)

直接在文档中使用它而不做任何假设(尽管如果您没有多个值的名称,那么不确定最终会得到什么)。这只是专门寻找基本元素,然后循环遍历<span>元素。每次在其中它都会查找itemNameitemValue类属性并从中获取值...

$output = [];
$filtered = $domxpath->query("//div[@class='item_list']/span");
foreach ( $filtered as $myItem )  {
    $name= $domxpath->evaluate("string(descendant::span[@class='itemName'])", $myItem);
    $value= $domxpath->evaluate("string(descendant::span[@class='itemValue'])", $myItem);
    $output[$name] = $value;
}
print_r($output);

推荐阅读