2 回答

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超1個(gè)贊
在 php 沙箱中,您的代碼有效。
但是,您忘記了標(biāo)簽<的開(kāi)頭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
你有價(jià)值href
(打印出來(lái))。
您似乎對(duì)字符串和使用'
and有疑問(wèn)"
。
$string
如果以with開(kāi)頭,'
則不能在內(nèi)部使用它。'
您可以在最后使用just 來(lái)關(guān)閉 php 變量';
;
你有三種解決方案:
在代表您的 html 的字符串中
'
替換;"
在代表您的 html 的字符串中使用
\'
instead of only 。'
這告訴 php 字符串尚未完成,但'
表示字符串內(nèi)容;heredoc 語(yǔ)法;
例如,對(duì)于第一種方法,我們有:
$string = ' Inside the string you should use just this type of apostrophe " ';

TA貢獻(xiàn)1793條經(jīng)驗(yàn) 獲得超6個(gè)贊
對(duì)于長(zhǎng)的多行字符串,我更喜歡切換到heredoc語(yǔ)法,它提供了一種更干凈/可見(jiàn)的方式來(lái)處理其中的字符串和引號(hào)。它還提供字符串的“所見(jiàn)即所得顯示”,因?yàn)榭梢园踩夭迦霌Q行符、制表符、空格、引號(hào)和雙引號(hào)。
我將您的示例切換為 HEREDOC 語(yǔ)法,并且運(yùn)行良好(結(jié)果正確),但由于您的 HTML 輸入格式錯(cuò)誤而導(dǎo)致的警告很少。
<?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 關(guān)注
- 130 瀏覽
添加回答
舉報(bào)