tags:

views:

55

answers:

2

i need php script to extract the ip address from the following xml page www.ip-address.com/test.xml

<dnstools>
<service_provider>Domain Tools</service_provider>
<provider_url>http://www.domaintools.com/&lt;/provider_url&gt;
<date>Wed, 12 May 2010 00:43:07 GMT</date>
<unix_time>1273624987</unix_time>
<ip_address>94.252.157.241</ip_address>
<hostname>94.252.157.241</hostname>
<blacklist_status>Clear</blacklist_status>
<remote_port>43577</remote_port>
<protocol>HTTP/1.0</protocol>
<connection>keep-alive</connection>
<keep_alive/>
A: 

A simple regex is easy enough for something like this.

preg_match_all('/(.*)/U', $xml_string, $matches);

Do a var_dump on $matches to see how it handles the output. If there's only one ip address in there(or you only need the first one), you can use preg_match() instead of preg_match_all()

Syntax Error
+1  A: 

Other alternative, especially when handling XML files, would be to use PHP's SimpleXML, this way you can traverse your XML tree structure easily. Could be as follows:

It is worth mentioning that if you are loading remote files you need, at your ini file, "allow_url_fopen" enabled.

allow_url_fopen = On

Assuming this is the XML being loaded

<?xml version="1.0" encoding="UTF-8"?>
<dnstools>
    <service_provider>Domain Tools</service_provider>
    <provider_url>http://www.domaintools.com/&lt;/provider_url&gt;
    <date>Wed, 12 May 2010 00:43:07 GMT</date>
    <unix_time>1273624987</unix_time>
    <ip_address>94.252.157.241</ip_address>
    <hostname>94.252.157.241</hostname>
    <blacklist_status>Clear</blacklist_status>
    <remote_port>43577</remote_port>
    <protocol>HTTP/1.0</protocol>
    <connection>keep-alive</connection>
    <keep_alive/>
</dnstools>

In your PHP file

$xml = simplexml_load_file('http://mydomain.com/test.xml');
echo $xml->children()->ip_address;

And you should get

94.252.157.241

As, you can see, using SimpleXML http://www.php.net/manual/en/book.simplexml.php it really gets simple :)

falomir
Thanks that's what i need exactly
Alaa
Cool, glad it helped, you could mark it as accepted:)
falomir