使用变量获取属性SimpleXML

时间:2012-06-09 10:48:01

标签: php xml variables simplexml

我想从一个特定的CollageObjectInfo元素获取PositionX属性的值,并且我有一个包含我想要选择的元素的数量的变量。

我想要实现的是这样的(当然这段代码不起作用):

$xml = simplexml_load_file("vars.xml");
$number = 140;
$positionx = $xml->CollageObjects->CollageObjectInfo[$number]->attributes()->PositionX;

参考资料来源:

<?xml version="1.0" encoding="utf-8"?>
<CollageInfo xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BgType="image" BgImagePath="http://localhost:8080/images/dreamboard/backgrounds/pattern2.jpg" BgColor="0" CanvasWidth="960" CanvasHeight="730" AutoSaveTime="50000" SelectedMemberDreamId="00000000-0000-0000-0000-000000000000">
  <CollageObjects>
    <CollageObjectInfo xsi:type="CollageImageInfo" 
                       MemberDreamId="a5d55cc1-8eb2-4e28-9ad9-4b9ea250926d" 
                       PositionX="670" PositionY="50" Rotation="0" 
                       ScaleX="0.5" ScaleY="0.5" Alpha="1" DropShadow="true"
                       Coords="670,77,887.5,77,887.5,337,670,337" 
                       Type="image" 
                       DreamboardImageId="00000000-0000-0000-0000-000000000000"
                       ImagePath="http://cubicflow.com/dan/dia/images/dream-1.jpg" 
                       Caption="I am flying without taking my shoes off." />
    <CollageObjectInfo xsi:type="CollageImageInfo" 
                       MemberDreamId="2f7a6c1b-6006-4a5d-b9d8-b653ee7ea4ca" PositionX="82" PositionY="323" Rotation="-40" ScaleX="0.5" ScaleY="0.5" Alpha="1" DropShadow="true" Coords="2,400,219.5,400,219.5,710,2,710" Type="image" DreamboardImageId="00000000-0000-0000-0000-000000000000" ImagePath="http://cubicflow.com/dan/dia/images/dream-2.jpg" Caption="I am continuing to improve physical conditioning." />
    <CollageObjectInfo xsi:type="CollageImageInfo" 
                       MemberDreamId="7230bb7a-58a6-49d3-bfc7-ed7e4486da85" PositionX="150" PositionY="404" Rotation="0" ScaleX="0.46" ScaleY="0.44" Alpha="1" DropShadow="true" Coords="680.75,381.25,880.85,381.25,880.85,736.75,680.75,736.75" Type="text" DreamboardImageId="00000000-0000-0000-0000-000000000000" ImagePath="" Caption="Lorem ipsum dolor yeeeeeeeahhhhssssss sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." />
  </CollageObjects>
</CollageInfo>

1 个答案:

答案 0 :(得分:-2)

您可以尝试使用XPath。

这样的东西
$attr = $xml->xpath('CollageObjects/CollageObjectInfo['.$number.']/@PositionX');

xpath()总是返回一个数组(如果出错则返回FALSE),所以你可以做类似的事情

$neededAttr = (string)$attr[0];

(当然在您检查错误后)

这是example


另一种可能的解决方案是:

$children = $x->CollageObjects->children();
echo $children[$number]->attributes()->PositionX;

或者如果您使用PHP&gt; = 5.4

echo $x->CollageObjects->children()[$number]->attributes()->PositionX

(我没有安装php 5.4,所以我不能保证代码能够正常工作,但我认为没有理由不这样做。)

PHP 5.4 Array dereferencing

注意:当PHP从0开始计算时,XPath从1开始计数,在使用$number作为索引时将其考虑在内。

祝你好运:)