php DOMDocument()->getAttribute()没有工作。

问题描述 投票:0回答:2

我想得到 href 的属性 a 标签的字符串。

我做了一个PHP小工具 此处 因为 string 太长了。

错误。

PHP Parse error:  syntax error, unexpected 'undefined' (T_STRING) in...
php html dom domdocument
2个回答
0
投票

在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. 使用 \' 而不是只 ' 内的字符串。这将告诉php这个字符串还没有完成,但是 ' 代表字符串内容。
  3. heredoc语法。

比如用第一种方法,我们有。

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


0
投票

对于长长的多行字符串,我更喜欢改用... 遗传性 语法,提供了一个更简洁可见的方式来处理字符串和引号。它还提供了一个"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');

完整的例子 分手.

希望能帮到你

© www.soinside.com 2019 - 2024. All rights reserved.