我有这个控制器:
<?php
namespace App'Http'Controllers;
class TestController extends Controller
{
public function index()
{
$html = file_get_html('http://www.somesite.com/');
$html->getElementsByTagName('article');
$anc = $html->find('a');
return view('welcome', compact($anc));
}
}
这个视图:
<!DOCTYPE html>
<html>
<head>
<title>Laravel</title>
</head>
<body>
<div class="container">
<div class="content">
@foreach($anc as $item)
{{ $item }} <br>
@endforeach
</div>
</div>
</body>
</html>
很简单,没什么特别的。只需获取url的内容,并使用一个简单的库对其进行解析,然后将变量anc
返回到welcome
视图,然后在视图中我尝试回显每个元素。它给了我:
ErrorException in 051dd3929cf86b31dbaacb340018a3c5 line 9:
Undefined variable: anc (View: C:'Users'User'Desktop'Project'resources'views'welcome.blade.php)
您使用compact()
不正确。正确的用法是:
return view('welcome', compact('anc'));
将要压缩的变量的名称作为字符串传递。
PHP文档:http://php.net/manual/en/function.compact.php
您在第一个代码块中错误地使用了compact()函数。试试这个。。。
class TestController extends Controller
{
public function index()
{
$html = file_get_html('http://www.somesite.com/');
$html->getElementsByTagName('article');
$anc = $html->find('a');
return view('welcome', compact('anc'));
}
}
紧凑函数需要变量的名称,而不是变量本身。