I have PHP script that fetches a list of IP-adresses from an URL, prepends and appends some text and linebreaks to it. This works well, except the source has an empty line at the end, and that makes a line without IP-adress. I need the script to ignore or delete that line, so that it is not generated.
<?php
$ipPage = file_get_contents('https://my.pingdom.com/probes/ipv4');
$ipList = explode("
", $ipPage);
echo "/ip firewall address-list
";
echo "remove [/ip firewall address-list find list=Pingdom]
";
foreach($ipList as $ip) {
echo "add address=" . $ip . " list=Pingdom
";
}
?>
You can see the result and the empty last line at https://novaram.dk/mikrotik.php
This
<?php
$ipPage = file_get_contents('https://my.pingdom.com/probes/ipv4');
$ipList = preg_split ( "
", $ipPage , -1 ,PREG_SPLIT_NO_EMPTY );
echo "/ip firewall address-list
";
echo "remove [/ip firewall address-list find list=Pingdom]
";
foreach($ipList as $ip) {
echo "add address=" . $ip . " list=Pingdom
";
}
?>
or this should work
<?php
$ipPage = file_get_contents('https://my.pingdom.com/probes/ipv4');
$ipList = explode("
", $ipPage);
echo "/ip firewall address-list
";
echo "remove [/ip firewall address-list find list=Pingdom]
";
foreach($ipList as $ip) {
if(strlen(trim($ip)) != 0 )
echo "add address=" . $ip . " list=Pingdom
";
}
?>
Alternatively, use implode()
to join them.
<?php
$ipPage = file_get_contents('https://my.pingdom.com/probes/ipv4');
$ipList = explode("
", $ipPage);
echo "/ip firewall address-list
";
echo "remove [/ip firewall address-list find list=Pingdom]
";
foreach($ipList as $ip) {
$ips[] = "add address={$ip} list=Pingdom";
}
echo implode("
", $ips);
?>
Thank you for all your answers, I got the following to work:
<?php
$ipPage = file_get_contents('https://my.pingdom.com/probes/ipv4');
$ipPage = str_replace("'","",$ipPage);
$ipList = explode("
", $ipPage);
echo "/ip firewall address-list
";
echo "remove [/ip firewall address-list find list=Pingdom]
";
foreach($ipList as $ip) {
if(strlen($ip) > 0) {
echo "add address=" . $ip . " list=Pingdom
";
}
}
?>
...but what I have a similar script, but the source sends me a list where I need to ignore the first line?