2 回答

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&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
(打印出來)。
您似乎對字符串和使用'
and有疑問"
。
$string
如果以with開頭,'
則不能在內部使用它。'
您可以在最后使用just 來關閉 php 變量';
;
你有三種解決方案:
在代表您的 html 的字符串中
'
替換;"
在代表您的 html 的字符串中使用
\'
instead of only 。'
這告訴 php 字符串尚未完成,但'
表示字符串內容;heredoc 語法;
例如,對于第一種方法,我們有:
$string = ' Inside the string you should use just this type of apostrophe " ';

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');
希望能幫助到你。
- 2 回答
- 0 關注
- 134 瀏覽
添加回答
舉報