Php xpath只获得头部

时间:2016-09-24 20:44:45

标签: php

我想使用xPath只获取head元素的内容。

//some curl request
$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

$DOM = new DOMDocument;
libxml_use_internal_errors(true);
if (!$DOM->loadHTML('<?xml encoding="utf-8" ?>' . $result)) {
    $errors = "";
    foreach (libxml_get_errors() as $error) {
        $errors .= $error->message . "<br/>";
    }
    libxml_clear_errors();
    print "libxml errors:<br>$errors";
    return;
}
$xpath = new DOMXPath($DOM);
$head = $xpath->query('//*["head"]')->item(0); // Any suggestions?

正如标题中所述,我正在使用PHP来尝试提取卷曲中的任何内容。欢迎任何建议。

1 个答案:

答案 0 :(得分:0)

如果您的卷曲响应符合预期,并且在XPath之前一切正常,请尝试:

$head = $xpath->query('/head/*');
foreach ($head as $headElement) {
    /* DO STUFF*/
}

您可能也不需要将<?xml encoding="utf-8" ?>添加到结果的开头。