我需要从XXML文件中过滤/搜索所有链接(png,jpg,mp3),但我被困在那里。我做了例如获取所有mp3,但我知道它存在,但是例如,如果我把其他文件放在路径不同的地方,那么它就不会检测到它。
foreach($xml->BODY->GENERAL->SOUNDS->SOUND as $a){
echo '<a href="'.$a->PATH.'">'.$a->PATH.'</a><br>';
}
答案 0 :(得分:1)
您可以获取每个文件的扩展名,并将其与一系列&#34;接受的扩展名&#34;进行比较。然后使用continue
跳过写链接:
$accepted_exts = ['png','jpg','mp3'];
foreach($xml->BODY->GENERAL->SOUNDS->SOUND as $a) {
$path = $a->PATH;
$ext = strtolower(substr($path, strrpos($path, '.') + 1));
if (!in_array($ext, $accepted_exts)) continue ; // continue to next iteration
echo '<a href="'.$path.'">'.$path.'</a><br>'; // write the link
}
获取其他链接:
$accepted_exts = ['png','jpg','mp3'];
$links = [] ;
foreach($xml->HEAD as $items) {
foreach ($items as $item) {
$path = (string)$item;
if (!in_array(get_ext($path), $accepted_exts)) continue ; // continue to next iteration
$links[] = $path ;
}
}
foreach($xml->BODY->GENERAL->SOUNDS->SOUND as $a) {
$path = $a->PATH;
if (!in_array(get_ext($path), $accepted_exts)) continue ; // continue to next iteration
$links[] = $path ;
}
foreach ($links as $path) {
echo '<a href="'.$path.'">'.$path.'</a><br>'; // write the link
}
function get_ext($path) {
return strtolower(substr($path, strrpos($path, '.') + 1));
}
输出:
<a href="http://player.glifing.com/img/Player/blue.png">http://player.glifing.com/img/Player/blue.png</a><br>
<a href="http://player.glifing.com/img/Player/blue_intro.png">http://player.glifing.com/img/Player/blue_intro.png</a><br>
<a href="http://player.glifing.com/upload/fondoinstrucciones2.jpg">http://player.glifing.com/upload/fondoinstrucciones2.jpg</a><br>
<a href="http://player.glifing.com/upload/stopbet2.png">http://player.glifing.com/upload/stopbet2.png</a><br>
<a href="http://player.glifing.com/upload/goglif2.png">http://player.glifing.com/upload/goglif2.png</a><br>
<a href="http://player.glifing.com/img/Player/Glif 3 OK.png">http://player.glifing.com/img/Player/Glif 3 OK.png</a><br>
<a href="http://player.glifing.com/img/Player/BetPensant.png">http://player.glifing.com/img/Player/BetPensant.png</a><br>
<a href="http://player.glifing.com/audio/Player/si.mp3">http://player.glifing.com/audio/Player/si.mp3</a><br>
<a href="http://player.glifing.com/audio/Player/no.mp3">http://player.glifing.com/audio/Player/no.mp3</a><br>
答案 1 :(得分:0)
为了节省必须知道哪些标签可能包含URL,您可以使用XPath搜索以&#34; http://&#34;开头的任何文本内容。或&#34; https://&#34;。然后处理每个部分以检查扩展名。
$xml = simplexml_load_file("data.xml");
$extensions = ['png', 'jpg', 'mp3'];
$links = $xml->xpath('//text()[starts-with(normalize-space(), "http://")
or starts-with(normalize-space(), "https://")]');
foreach ( $links as $link ) {
$link = trim(trim($link),"_");
$path = parse_url($link, PHP_URL_PATH);
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
if ( in_array($extension, $extensions)) {
// Do something
echo $link.PHP_EOL;
}
else {
echo "Rejected:".$link.PHP_EOL;
}
}
我发现使用trim()
帮助清理后面有空白行的URL(或至少一些额外的空格)。并将它们全部转换为更低,以便更容易检查。
您可能不需要被拒绝的位,但我将其用于测试我的代码。
您必须重复以上