【发布时间】:2012-03-18 03:33:30
【问题描述】:
我有一个 XML sn-p,它有一个 URL 分段的部分,如下所示。我可以使用 SimpleXML 和 XPath 成功解析它。我的 XPath 查询返回一个包含结果的数组,然后我可以回显它们。没有问题! =)
但是,我想进一步尝试减少代码行并改进我的代码。先看看我的代码:
<?php
$xml_g='
<files>
<file>
<filename>itzafile</filename>
<ext>.tar.gz</ext>
<url protocol="http://">itzanexample.net/folder/subfolder/</url>
</file>
<file>
<filename>itzavideo</filename>
<ext>.mp4</ext>
<url protocol="ftp://">itzanotherurl.com/videos/</url>
</file>
</files>
';
function URLparts($xml) {
$xmlData= simplexml_load_string("$xml");
$protocol = $xmlData->xpath('//file/url/@protocol');
$url = $xmlData->xpath('//file/url');
$filename = $xmlData->xpath('//file/filename');
$ext = $xmlData->xpath('//file/ext');
echo 'The following it\'s echoed calling 4 different arrays:'."\n\t".$protocol[0], $url[0], $filename[0], $ext[0]."\n\t".$protocol[1], $url[1], $filename[1], $ext[1]."\n\n"; //prints the entire url! Right!
//These variables are arrays, so theoretically it must be possible to create an array of arrays here:
$completeURL = array($protocol,$url,$filename,$ext);
//I've also tried this but it's just the same problem:
//$completeURL = array(array($protocol),array($url),array($filename),array($ext));
echo 'The following should be echoed with a two-dimensional array, but something fails:'."\n\t".$completeURL[0][0][0][0]."\n\n"; //Just prints "http://" WRONG! u.u
/*
* $completeURL[1][0][0][0] prints the domain+subfolder
* $completeURL[0][1][0][0] prints ftp://
* $completeURL[0][0][1][0] prints nothing...
*/
}
URLparts($xml_g);
?>
如您所见,我想避免将 URL 加入为:echo $protocol[0]、$url[0]、$filename[0]、$ext[0],并且我想用更少的代码更简单地完成它变量,如 completeURL[0][0][0][0] (第一个文件节点及其所有相应部分), completeURL[1][1][1][1] (第二个文件节点,所有 url 部分)等等……
但显然我做错了什么。错误在哪里?它应该与我要创建的多维数组有关。
【问题讨论】:
标签: php xpath multidimensional-array xml-parsing simplexml