php DOMDocument()->getAttribute() 不工作

php DOMDocument()->getAttribute() not working

我想从字符串中的 HTML 获取 a 标签的 href 属性的值。

我做了一个PHPfiddlehere因为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&amp;COUNTY=san francisco&amp;YEARSEGMENT=current&amp;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 变量 ';;

您有三种解决方案:

  1. 在表示您的 html;
  2. 的字符串中用 " 替换 '
  3. 在表示您的 html 的字符串中使用 \' 而不是仅使用 '。这告诉php字符串还没有完成但是'表示字符串内容;
  4. heredoc 语法;

例如第一种方法我们有:

$string = ' Inside the string you should use just this type of apostrophe " ';

对于较长的多行字符串,我更喜欢切换到 heredoc 语法,它提供了一种更 clean/visible 的方式来处理其中的字符串和引号。它还提供字符串的“WYSIWYG 显示”,因为可以安全地插入换行符、制表符、空格、引号和双引号。

我将您的示例切换为 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');

separate fiddle 中的完整示例。

希望对您有所帮助。