如何使用xpath映射这些字段?

时间:2012-01-10 13:07:19

标签: php xpath

我正在尝试使用php DOMXPath对象从网站映射一个字段列表,我正在努力。 我试图通过绝对位置读取,但是当字段丢失时它会中断,并且我认为可以使用由强标记分隔的字段名称来查找正确的值。 我怎样才能做到这一点?

网站示例:

<div class="container">
    <strong>field1: </strong>
    <a href="http://link/1">value1</a>
    <a href="http://link/2">value2</a>
    <br>
    <strong>field2:</strong>
    <a href="http://link/3">value3</a>
    <br>
    <strong>field3:</strong>
    <a href="http://link/4">value4</a>
</div>

我需要类似的东西:

array = {
    field1 => 
        array = {
            'value1',
            'value2'
        },
    field2 => 'value3',
    field3 => 'value4'
}

or

array = {
    field1 => 'value1 value2',
    field2 => 'value3',
    field3 => 'value4'
}

一个工作的例子是最令人沮丧的,因为我正在开始讨论这个问题。

1 个答案:

答案 0 :(得分:1)

$dom = new DOMDocument();
$dom->loadHTML($str); // Or however you load your HTML

$xpath = new DOMXPath($dom);
$items = $xpath->query('//div[@class = "container"]/strong');


$arr = array();
for($i = 0; $i < $items->length; $i++)
{
    $node = $items->item($i);
    $name = trim($node->nodeValue, ': ');
    $node_items = array();
    while(true)
    {
        $node = $node->nextSibling->nextSibling;
        if($node == NULL || $node->nodeName != 'a')
        {
            break;
        }
        $node_items[] = $node->nodeValue;
    }

    $arr[$name] = count($node_items) == 1 ? $node_items[0] : $node_items;
}

给出结果($arr):

Array
(
    [field1] => Array
        (
            [0] => value1
            [1] => value2
        )

    [field2] => value3
    [field3] => value4
)