0

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("\n", $ipPage);
echo "/ip firewall address-list\n";
echo "remove [/ip firewall address-list find list=Pingdom]\n";
foreach($ipList as $ip) {
    echo "add address=" . $ip . " list=Pingdom\n";
  }
?>

You can see the result and the empty last line at https://novaram.dk/mikrotik.php

Ulski
  • 1
  • 1
    maybe try using `array_filter` just after exploding? Like: `$ipList = array_filter(explode("\n", $ipPage))`. It will remove every item with a value that equals false –  Sep 18 '17 at 14:51
  • Possible duplicate of [Remove empty array elements](https://stackoverflow.com/questions/3654295/remove-empty-array-elements) – Maraboc Sep 18 '17 at 14:56
  • Also you could just check if the `$ip` var is truthy, like `foreach ($ipList as $ip) { if ($ip) { echo "...."; } }`, or use trim `$ipPage = trim($ipPage);`. – Parziphal Sep 18 '17 at 14:57

3 Answers3

1

Alternatively, use implode() to join them.

<?php
$ipPage = file_get_contents('https://my.pingdom.com/probes/ipv4');
$ipList = explode("\n", $ipPage);
echo "/ip firewall address-list\n";
echo "remove [/ip firewall address-list find list=Pingdom]\n";
foreach($ipList as $ip) {
    $ips[] = "add address={$ip} list=Pingdom";
}

echo implode("\n", $ips);
?>
Daren Chandisingh
  • 2,157
  • 1
  • 13
  • 17
0

This

<?php
$ipPage = file_get_contents('https://my.pingdom.com/probes/ipv4');
$ipList = preg_split ( "\n", $ipPage , -1 ,PREG_SPLIT_NO_EMPTY );
echo "/ip firewall address-list\n";
echo "remove [/ip firewall address-list find list=Pingdom]\n";
foreach($ipList as $ip) {
    echo "add address=" . $ip . " list=Pingdom\n";
  }
?>

or this should work

<?php
$ipPage = file_get_contents('https://my.pingdom.com/probes/ipv4');
$ipList = explode("\n", $ipPage);
echo "/ip firewall address-list\n";
echo "remove [/ip firewall address-list find list=Pingdom]\n";
foreach($ipList as $ip) {
    if(strlen(trim($ip)) != 0 )
        echo "add address=" . $ip . " list=Pingdom\n";
  }
?>
bassxzero
  • 4,838
  • 22
  • 34
0

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("\n", $ipPage);
echo "/ip firewall address-list\n";
echo "remove [/ip firewall address-list find list=Pingdom]\n";
foreach($ipList as $ip) {
    if(strlen($ip) > 0) {
        echo "add address=" . $ip . " list=Pingdom\n";
    }
}
?>

...but what I have a similar script, but the source sends me a list where I need to ignore the first line?

Ulski
  • 1