duankekan9269
2016-01-05 19:01
浏览 111
已采纳

Laravel 5.1 - 视图中的未定义变量

I have this controller:

<?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));
    }
}

and this view :

<!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>

Very simple and nothing special. just getting contents of a url and parsing it with a simple library and returning variable anc to the welcome view and then in the view i'm trying to echo each element. it gives me:

ErrorException in 051dd3929cf86b31dbaacb340018a3c5 line 9:
Undefined variable: anc (View: C:\Users\User\Desktop\Projectesources\views\welcome.blade.php)

图片转代码服务由CSDN问答提供 功能建议

我有这个控制器:

 &lt;?php \  n 
namespace App \ Http \ Controllers; 
 
class TestController扩展Controller 
 {
公共函数索引()
 {
 $ html = file_get_html('http://www.somesite.com/');  
 $ html-&gt; getElementsByTagName('article'); 
 $ anc = $ html-&gt; find('a'); 
 
返回视图('welcome',compact($ anc)); \  n} 
} 
   
 
 

此视图:

 &lt;!DOCTYPE html&gt; 
&lt; html&gt  ; 
&lt; head&gt; 
&lt; title&gt; Laravel&lt; / title&gt; 
&lt; / head&gt; 
&lt; body&gt; 
&lt; div class =“container”&gt; 
&lt; div class =  “content”&gt; 
 @foreach($ anc as $ item)
 {{$ item}}&lt; br&gt; 
 @endforeach 
&lt; / div&gt; 
&lt; / div&gt; 
&lt;  / body&gt; 
&lt; / html&gt; 
   
 
 

很简单,没什么特别的。 只需获取一个url的内容并使用一个简单的库解析它并将变量 anc 返回到 welcome 视图,然后在视图中我试图回显每个元素。 它给了我:

  051dd3929cf86b31dbaacb340018a3c5第9行中的ErrorException:
未定义的变量:anc(查看:C:\ Users \ User \ Desktop \ Project 
esources \ views \ welcome.blade  .php)
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongxun7962 2016-01-05 19:07
    已采纳

    You're using compact() improperly. Correct usage is this:

    return view('welcome', compact('anc'));
    

    Pass the names of the variables you want compacted, as strings.

    PHP doc: http://php.net/manual/en/function.compact.php

    打赏 评论
  • doulin6761 2016-01-05 19:09

    You are using the compact() function in your first block of code incorectly. Try this...

    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'));
            }
     }
    

    The compact function requires the name of the variable, not the variable itself.

    打赏 评论

相关推荐 更多相似问题