我想得到 href
的属性 a
标签的字符串。
我做了一个PHP小工具 此处 因为 string
太长了。
错误。
PHP Parse error: syntax error, unexpected 'undefined' (T_STRING) in...
在php沙盒中,你的代码可以工作。
然而,你忘记了 <
一开始 a
标签。
<?php
$string = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
</head>
<body onclick="on_body_click()" text="#000000" alink="#FF0000" link="#0000FF" vlink="#800080">
<a href="/cgi-bin/new_get_recorded.cgi?l_doc_ref_no=7506389&COUNTY=san francisco&YEARSEGMENT=current&SEARCH_TYPE=DETAIL_N" title="Document Details">Show Name Detail</a>
</body>
</html>';
$doc = new DOMDocument();
$doc->loadHTML($string);
$selector = new DOMXPath($doc);
$result = $selector->query('//a[@title="Document Details"]');
$url = $result[0]->getAttribute('href');
echo $url;
在 $url
你有 href
值(打印出来)。
看来你对字符串和使用的 '
和 "
.
如果你启动 $string
与 '
你不能在里面使用它。你可以使用 '
在最后关闭php变量 ';
;
你有三种解决方案。
'
与 "
在代表您的 html 的字符串中。\'
而不是只 '
内的字符串。这将告诉php这个字符串还没有完成,但是 '
代表字符串内容。比如用第一种方法,我们有。
$string = ' Inside the string you should use just this type of apostrophe " ';
对于长长的多行字符串,我更喜欢改用... 遗传性 语法,提供了一个更简洁可见的方式来处理字符串和引号。它还提供了一个"WYSIWYG 字符串的 "display",因为它可以安全地插入换行符、制表符、空格、引号和双引号。
我把你的例子换成了HEREDOC语法,它运行得很好(结果正确),只是由于你的HTML输入错误而出现了一些警告。
<?php
$string = <<<HTMLINPUT
Your multi-line HTML input goes here.
HTMLINPUT;
$doc = new DOMDocument();
$doc->loadHTML($string);
$selector = new DOMXPath($doc);
$result = $selector->query('//a[@title="Document Details"]');
echo $url = $result[0]->getAttribute('href');
完整的例子 分手.
希望能帮到你