-1

我想从一个特定的 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>
4

1 回答 1

-2

您可以尝试使用 XPath。

就像是

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

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

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

(当然是在你检查错误之后)

这是一个例子


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

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

或者如果你使用 PHP >= 5.4

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

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

PHP 5.4 数组解引用

注意:$number XPath 从 1 开始计数,而 PHP 从 0 开始计数,在使用as 索引时要考虑到这一点。

祝你好运 :)

于 2012-06-13T15:43:36.743 回答