【发布时间】:2017-08-21 10:27:18
【问题描述】:
我正在尝试在我的 foreach 循环中使用 if/else 语句。 使用 DomDocument 我试图找到描述标签和描述标签的内部。
这很好用。当有描述标签时,它会显示描述标签内的内容。如果没有描述标签,则会显示:No description found No description found No description found No description found。为什么它显示错误四次?我该如何解决这个问题?
我正在使用 DomDocument 和 Laravel 5.4
元标记:
$meta = $dom->getElementsByTagName('meta');
我的代码:
@foreach ($meta as $node)
@if($node->getAttribute('name')=='description')
{{$node->getAttribute('content'), PHP_EOL}}
@else
{{'No description found'}}
@endif
@endforeach
编辑,根据 Muthu17:
我几乎写了和你一样的代码。但唯一的问题是:它一直显示“找不到描述”。即使找到描述标签,它也会显示描述标签初始化和“未找到描述”。
我已经在我的控制器中声明了$showErrorMessage = 0;。
@foreach ($meta as $node)
@if($node->getAttribute('name')=='description')
{{$node->getAttribute('content'), PHP_EOL}}
@else
{!! $showErrorMessage == 1; !!}
@endif
@endforeach
@if($showErrorMessage = 1)
{{'No description found'}}
@endif
【问题讨论】:
-
{{$node}} 提供了什么?
-
您的循环包含 3 个项目,这三个项目没有描述,因此您收到 3 次“未找到描述”消息
-
@pseudoanime 感谢您的提问。我已经更新了我的帖子!
-
@muthu17 我想到了,但我该如何解决这个问题?
-
在为每个创建一个变量之前,例如:showErrorMessage = 0 并且在内部其他只是将值更改为 1 [ showErrorMessage = 0 ] 在每个结束后检查 showErrorMessage 状态并打印消息
标签: if-statement foreach domdocument laravel-blade