为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕盖茨4494581 2023-04-21 09:57:48
我想从字符串中的 HTML 中获取标签href属性的值。a我在这里制作了一个 PHP 小提琴,因为它string太长了。错误:PHP Parse error:  syntax error, unexpected 'undefined' (T_STRING) in...
查看完整描述

2 回答

?
慕神8447489

TA贡献1780条经验 获得超1个赞

在 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">

            <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(打印出来)。

您似乎对字符串和使用'and有疑问"

$string 如果以with开头,'则不能在内部使用它。'您可以在最后使用just 来关闭 php 变量';

你有三种解决方案:

  1. 在代表您的 html 的字符串中'替换;"

  2. 在代表您的 html 的字符串中使用\'instead of only 。'这告诉 php 字符串尚未完成,但'表示字符串内容;

  3. heredoc 语法;

例如,对于第一种方法,我们有:

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


查看完整回答
反对 回复 2023-04-21
?
摇曳的蔷薇

TA贡献1793条经验 获得超6个赞

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

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

希望能帮助到你。


查看完整回答
反对 回复 2023-04-21
  • 2 回答
  • 0 关注
  • 73 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信