无法让 preg_match() 从另一个网站获取内容


Can't get preg_match() to work to fetch content from another website

我正在尝试从带有标签和preg_match()正则表达式的外部网站获取值,但它不起作用。

我的代码

$file = file_get_contents('http://www.investing.com/indices/us-spx-500');
$regexp = '/'<span class'='"arial_26 inlineblock pid-166-last'" id'='"last_last'" dir'='"ltr'"'>(.*?)'<'/span>/';
preg_match($regexp, $file, $string1);
print_r(array_values($string1));

我需要匹配的标签是:

<span class="arial_26 inlineblock pid-166-last" id="last_last" dir="ltr">1,880.02</span>

1,880.02 = (.*?)

我需要获取标准普尔500指数的价值。我知道这可能是版权问题。这仅供私人使用。正如您在$regexp中看到的,我需要转义所有已完成的特殊字符。我尝试从 TXT 文件中获取标签并且它正在工作,所以我知道代码是正确的/链接的。一定是正则表达式的问题。有人能弄清楚,还是我错过了什么?数组为空。

我以为是因为课堂上有空格,所以我尝试's但没有奏效。

我也尝试了以下方法,但没有进展:

$regexp = '#<span class="arial_26 inlineblock pid-166-last" id="last_last" dir="ltr">(.*?)</span>#';

如果您从网站上检查源代码,它应该是该特定标签。

提前谢谢。

PHP 有内置工具来解析 HTML,正则表达式在这里特别不合适,因为你正在寻找一个带有 id 属性的节点!

// you set the user_agent with the name you want
$opts = [ 'http' => [ 'user_agent' => 'obliglobalgu' ] ];
// to create a stream context 
$context = stream_context_create($opts);
// set the stream context for DOMDocument::loadHTMLFile 
libxml_set_streams_context($context); 
$url = 'http://www.investing.com/indices/us-spx-500';
libxml_use_internal_errors(true); // avoid eventual libxml errors to be displayed
$dom = new DOMDocument;
$dom->loadHTMLFile($url);
$spanNode = $dom->getElementById('last_last');
if ($spanNode)
    echo $spanNode->nodeValue;
libxml_clear_errors();

它不起作用,因为如果您不向其传递用户代理 investing.com 它不会返回任何内容。以下代码工作正常:

$options = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en'r'n" .
              "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10'r'n" // i.e. An iPad 
  )
);
$context = stream_context_create($options);
$file = file_get_contents('http://www.investing.com/indices/us-spx-500',false,$context);
$regexp = '/'<span class='"arial_26 inlineblock pid-166-last'" id='"last_last'" dir'='"ltr'"'>(.*?)<'/span>/';
preg_match($regexp, $file, $string1);
print_r(array_values($string1));

此外,您只需要在该字符串中转义 "/,无需转义 =<>