xpath查询没有结果

时间:2013-06-26 12:29:15

标签: php html dom xpath

我正在尝试从dom中为我的某个页面动态更改/更新元描述。所以我尝试了以下方式,

libxml_use_internal_errors(true); //I'm not sure this is helpful
$xpath = new DOMXPath($dom); 
$name = 'desciption';
$query = '/html/head/meta[@name=\''.$name.'\']/@content';
$contents = $xpath->query($query);
echo $contents->item(0)->value; //blank :(

这里我无法获取元描述的内容值。

  • 我查了htmlspecialchars($dom)&这似乎是正确的。
  • 我检查了页面的视图来源& desciption在html-> head-> meta中 标记(页面标记的pastebin)。

任何人都可以帮我解决这里的问题吗?我的查询有什么问题吗?

1 个答案:

答案 0 :(得分:3)

对我来说,当用双引号引用alue时,让我们发一个例子,因为它在评论中没有说清楚。

我创建了一个文件html.html

<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="description" content="some content">
    </head>
    <body>
        <div>TODO write content</div>
    </body>
</html>

然后是php:

<?php
$file = "html.html";
$dom = new DOMDocument();
$dom->loadHTMLFile($file);
$xpath = new DOMXPath($dom); 
$name = 'description';
$query = '/html/head/meta[@name="'.$name.'"]/@content';
$contents = $xpath->query($query);
echo $contents->item(0)->value;
?>

输出为some content

你需要在第一个双引号之后关闭单引号,这样它们将保留在引用的字符串中,然后放入变量,开始引用并再次放双引号

编辑:

我使用了发布网站上的HTML:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css" media="screen">
<!--
#qm0 {position:relative;}
                    #qm0 a {display:block; white-space:nowrap; }
                    #qm0 div a {float:none;}
                    #qm0 div {visibility:hidden;position:absolute;}
                    #qm0 a {float: left; }
-->
</style>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Product1 Name</title>
<link href="n-defaultStyle.css" rel="stylesheet" type="text/css">
<meta http-equiv="pragma" content="no-cache">
<meta name="keywords" content=" Ilmfpnv, VrbfZgj, Fsikeprr Mluw">
<meta name="description" content="Beu Urb Hcsmihnurb cl c avlqclb ZtatcZq nrbc in unidrdpt cft mbvfp kj rmi isspulu. Uqwoiab in sf upq lkspuj jZ oed diirovs">
</head>

仍然没有问题,输出:

Beu Urb Hcsmihnurb cl c avlqclb ZtatcZq nrbc in unidrdpt cft mbvfp kj rmi isspulu. Uqwoiab in sf upq lkspuj jZ oed diirovs

相关问题