在PHP中,如何根据变量获取XML属性?

Jod*_*ren 1 php xml variables

我正在检索这样的文件(来自Internet Archive):

<files>
  <file name="Checkmate-theHumanTouch.gif" source="derivative">
    <format>Animated GIF</format>
    <original>Checkmate-theHumanTouch.mp4</original>
    <md5>72ec7fcf240969921e58eabfb3b9d9df</md5>
    <mtime>1274063536</mtime>
    <size>377534</size>
    <crc32>b2df3fc1</crc32>
    <sha1>211a61068db844c44e79a9f71aa9f9d13ff68f1f</sha1>
  </file>
  <file name="CheckmateTheHumanTouch1961.thumbs/Checkmate-theHumanTouch_000001.jpg" source="derivative">
    <format>Thumbnail</format>
    <original>Checkmate-theHumanTouch.mp4</original>
    <md5>6f6b3f8a779ff09f24ee4cd15d4bacd6</md5>
    <mtime>1274063133</mtime>
    <size>1169</size>
    <crc32>657dc153</crc32>
    <sha1>2242516f2dd9fe15c24b86d67f734e5236b05901</sha1>
  </file>
</files>
Run Code Online (Sandbox Code Playgroud)

他们可以拥有任意数量的<file>s,而我只是在寻找缩略图.当我找到它们时,我想增加一个计数器.当我浏览整个文件时,我想找到中间缩略图并返回name属性.

这是我到目前为止所得到的:

//pop previously retrieved XML file into a variable
$elem = new SimpleXMLElement($xml_file);
//establish variable
$i = 0;

// Look through each parent element in the file
foreach ($elem as $file) {
    if ($file->format == "Thumbnail"){$i++;}
}
    //find the middle thumbnail.
$chosenThumb = ceil(($i/2)-1);
    //Gloriously announce the name of the chosen thumbnail.
echo($elem->file[$chosenThumb]['name']);`
Run Code Online (Sandbox Code Playgroud)

最终的回声不起作用,因为它不喜欢选择XML元素的变量.当我对其进行硬编码时,它工作正常.您能猜出我是处理XML文件的新手吗?

编辑:弗朗西斯阿维拉的答案从下面排除了我!

$sxe = simplexml_load_file($url);
$thumbs = $sxe->xpath('/files/file[format="Thumbnail"]');
$n_thumbs = count($thumbs);
$middlethumb = $thumbs[(int) ($n_thumbs/2)];
$happy_string = (string)$middlethumb[name];
echo $happy_string;
Run Code Online (Sandbox Code Playgroud)

Fra*_*ila 5

使用XPath.

$sxe = simplexml_load_file($url);
$thumbs = $sxe->xpath('/files/file[format="Thumbnail"]');
$n_thumbs = count($thumbs);
$middlethumb = $thumbs[(int) ($n_thumbs/2)];
$middlethumbname = (string) $middlethumb['name'];
Run Code Online (Sandbox Code Playgroud)

如果您不需要总计数,也可以使用单个XPath表达式完成此操作:

$thumbs = $sxe->xpath('/files/file[format="Thumbnail"][position() = floor(count(*) div 2)]/@name');
$middlethumbname = (count($thumbs)) ? $thumbs[0]['name'] : '';
Run Code Online (Sandbox Code Playgroud)

SimpleXML的xpath方法的局限在于它只能返回节点而不是简单类型.这就是你需要使用的原因$thumbs[0]['name'].如果您使用DOMXPath::evaluate(),您可以这样做:

$doc = new DOMDocument();
$doc->loadXMLFile($url);
$xp = new DOMXPath($doc);
$middlethumbname = $xp->evaluate('string(/files/file[format="Thumbnail"][position() = floor(count(*) div 2)]/@name)');
Run Code Online (Sandbox Code Playgroud)