【问题标题】:foreach laravel error after using curl json output使用 curl json 输出后 foreach laravel 错误
【发布时间】:2018-10-19 23:11:41
【问题描述】:

这是我的控制器代码

$curl = new Curl();
$curl->setUrl('http://localhost:8001/scrape');
$curl->execute();
$data = json_decode(file_get_contents('output.json'));
return view('data-scraping', compact('data'));

我在那个 8001 端口使用数据抓取器 这是我的 output.json

[
    {
        "rank": 1,
        "title": "Did Facebook’s faulty data push publishers to make terrible decisions on video?",
        "url": "http://www.niemanlab.org/2018/10/did-facebooks-faulty-data-push-news-publishers-to-make-terrible-decisions-on-video/",
        "points": 59,
        "username": "laurex",
        "comments": 1
    }
]

最后是我的刀片模板中的一个 foreach

@foreach($data as $key => $value)
    <div class="col-sm-12">
        <a href="{!! $value->url !!}">
            <h3 class="title">{!! $value->title !!}</h3>
        </a>
        <p class="text-muted">
            <strong>Points :</strong> {!! $value->points !!}
            <strong>Comments :</strong> {!! $value->comments !!}
        </p>
        <p class="text-muted">Posted by <a href="#">{!! $value->username !!}</a></p>
    </div>
@endforeach

但是当我加载我的网页时,问题

Invalid argument supplied for foreach() (View: F:\XAMPP\htdocs\test\resources\views\data-scraping.blade.php)

当我在刀片视图中使用 dd() 时,返回 none 但有一个 output.json 文件。

如果我评论 curl 函数并使用可以正常工作的预构建 json 文件

我该如何处理?

【问题讨论】:

  • 你能用‘curl_error’ 方法检查卷曲错误吗?另外,你的 output.json 的路径是什么?
  • @joelrosenthal curl_error 返回空字符串。 output.json 路径是 public/output.json 。每个部分单独工作正常。如果我只是从工作的控制器读取 json 数据。甚至 curl 创建我的 json 文件。当我一个接一个地使用它们时会抛出错误

标签: php laravel curl


【解决方案1】:

尝试传递 true 作为 json_decode 的第二个参数。 $data = json_decode(file_get_contents('output.json'), true);

【讨论】:

  • 如果您尝试打印 $data 变量会得到什么?您是否尝试过将此结果放入在线 json 在线验证器中,例如 jsoneditoronline.orgjsonlint.com
  • dd($data) 在此代码之后 $data = json_decode(file_get_contents('output.json')); 显示我的数据。但在此代码之后$curl = new Curl(); $curl-&gt;setUrl('http://localhost:8001/scrape'); $curl-&gt;execute(); $data = json_decode(file_get_contents('output.json') , true); 为空
  • 我认为使用 curl_close 会有所帮助。我看到你正在使用一个我不知道它是由 laravel 提供的 Curl 类,可能类似于 $curl->close()。
【解决方案2】:

您可能需要设置CURLOPT_RETURNTRANSFER 选项。就像是 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);。如果您仍然没有得到任何响应,则可能是 json 解码问题,需要您使用json_last_error 方法进行故障排除。

【讨论】:

    猜你喜欢
    • 2015-03-29
    • 2017-06-16
    • 2014-10-20
    • 2019-06-26
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    相关资源
    最近更新 更多