我不能使用Twig点表示法访问对象属性。例如,从对象转储的角度来看,我应该能够做image.copyright,它应该为第一项打印“在开曼群岛附近的蓝色按钮,加勒比((C) Lawson Wood/Aurora Photos)”。
我得到的错误信息是
对象"SimpleXMLElement“的”版权“方法在第12行的ARRaiDesignBundle:Default:wallpapers.html.twig中不存在
使用转储(映像)转储对象时,转储每个对象。
控制器类:
$host = 'http://www.bing.com';
$file = $host . '/HPImageArchive.aspx?format=xml&idx=0&n=10&mkt=en-US';
$xml = simplexml_load_file($file);
return $this->render('ARRaiDesignBundle:Default:wallpapers.html.twig', array('xml' => $xml, 'host' => $host));wallpapers.html.twig文件:
...
{% for image in xml %}
<p><pre>{{ image.copyright }}</pre></p>
{% endfor %}
...使用Twig中的转储(图像)转储对象:
object(SimpleXMLElement)#268 (12) {
["startdate"]=>
string(8) "20130330"
["fullstartdate"]=>
string(12) "201303300000"
["enddate"]=>
string(8) "20130331"
["url"]=>
string(46) "/az/hprichbg/rb/BlueButton_EN-US1108621411.jpg"
["urlBase"]=>
string(43) "/az/hprichbg/rb/BlueButton_EN-US10208337365"
["copyright"]=>
string(77) "Blue button near the Cayman Islands, Caribbean (© Lawson Wood/Aurora Photos)"
["copyrightlink"]=>
string(74) "http://www.bing.com/search?q=Blue+Button+%28Porpita+porpita%29&form=hpcapt"
["drk"]=>
string(1) "1"
["top"]=>
string(1) "1"
["bot"]=>
string(1) "1"
...有人能建议怎么做吗?我知道我可以使用PHP呈现而不是Twig,但这对我来说不是一个解决办法。谢谢。
发布于 2013-03-30 19:14:56
这是因为Bing的werid XML结构,最后一点并不是迭代友好的。对于标准PHP来说,这很好,但是对于Twig,它不会捕捉到最后一个元素的错误。
<images>
<image>...</image>
<image>...</image>
<image>...</image>
<image>...</image>
<image>...</image>
<image>...</image>
<image>...</image>
<image>...</image>
<tooltips>...</tooltips>
</images>为了解决这个问题,我只是取消了工具提示。“unset($xml->工具提示)”
感谢@JaredFarrish提供了干净的xml。:)
发布于 2014-01-16 10:52:12
使用示例php http://www.php.net/manual/fr/simplexml.examples-basic.php
在细枝中,要从“评级”项中获取属性“type”,请使用属性(="@ attributes ")如下:
{% for rating in movies.movie.rating %}
{{ rating.attributes.type }}
{% endfor %}发布于 2013-03-30 16:00:46
在我看来,您的SimpleXMLElement似乎没有实现神奇的方法。当您调用Twig object.property时,它调用object的getProperty()方法。尝试在Twig中直接访问属性:
{{ image['copyright'] }}https://stackoverflow.com/questions/15720201
复制相似问题