http://api.hostip.info/?ip=87.14.94.152
From this link (xml) i am tried to retrive countryName and countryAbbrev like this:
$url = 'http://api.hostip.info/?ip=87.14.94.152';
$xml = simplexml_load_file($url) or die("feed not loading");
$Country = $xml->gml['featureMember']->Hostip->countryName;
echo $Country;
echo 'BREAK HTML';
echo "-----";
echo "// "; var_dump($xml); echo " //";
but $Country is blank, any idea about?
thanks in advance
Try this not like an answer, but, just another way to do the same:
$data = file_get_contents('http://api.hostip.info/get_html.php?ip=87.14.94.152&position=true');
$arrayofdata = explode("\n", $data);
$country = explode(":", $arrayofdata[0]);
$count = explode(" ", $country[1]);
echo "Country Name: ".$count[1]."</br>"; //Prints ITALY
echo "Country Abbv: ".trim($count[2],"()"); //Prints IT
The position=true url part, it's just in case that you want to retrieve the coordinates.
Cheers ;)
Try this:
$url = 'http://api.hostip.info/?ip=87.14.94.152';
$xml = simplexml_load_file($url) or die("feed not loading");
$fm=$xml->xpath('//gml:featureMember');
print_r($fm[0]->Hostip->countryName);
Make a local copy of the xml and it will work. Just tested this and got the data back:
$url = 'http://api.hostip.info/?ip=87.14.94.152';
$data = file_get_contents($url);
$xml = simplexml_load_file($data) or die("feed not loading");
The countryName node is nested in a deeper level. You can use the children() method to access attributes with colon. Here's how you can get the country name:
$countryName = (string) $xml->children('gml', true)
->featureMember->children('', true)
->Hostip->countryName; // => ITALY
You could also use an XPath expression to retrieve the country name. This is easier:
$hostip = $xml->xpath('//Hostip');
$countryName = $hostip[0]->countryName; // => ITALY
$countryAbbrev = $hostip[0]->countryAbbrev; // => IT
protected function getCountryNameFromIP()
{
$ip = $_SERVER['REMOTE_ADDR'];
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
$answerIP = #file_get_contents("http://api.ipinfodb.com/v3/ip-country/?key=4b585e37503a519a408dc17878e6ec04fa963e1b946c567722538d9431c2d5cb&format=xml&ip=$ip" ,false,$context);
if(isset($answerIP) && $answerIP !="")
{
$theResJ = simplexml_load_string($answerIP);
$last_login_ip_cn = $theResJ->countryName;
/**
* $last_login_ip_cc = $theResJ->countryCode;
* $last_login_ip_rc = $theResJ->regionCode;
* $last_login_ip_rn = $theResJ->regionName;
* $last_login_ip_cp = $theResJ->cityName;
* $last_login_ip_lat = $theResJ->latitude;
* $last_login_ip_lng = $theResJ->longitude;
* $last_login_zip_code= $theResJ->zipCode;
*/
}
else
{
$last_login_ip_cn = "";
/**
* $last_login_ip_cc = "";
* $last_login_ip_rc = "";
* $last_login_ip_rn = "";
* $last_login_ip_cp = "";
* $last_login_ip_lat = "";
* $last_login_ip_lng = "";
* $last_login_zip_code= "";
*/
}
return $last_login_ip_cn;
}
I hope it helps you
I agree. I just tried both answers and got good results. Here is the test code I just ran:
<?php
$url = 'http://api.hostip.info/?ip=87.14.94.152';
// $data = file_get_contents($url);
$xml = simplexml_load_file($url) or die("feed not loading");
// $Country = $xml->gml['featureMember']->Hostip->countryName;
// echo $Country;
echo 'BREAK HTML';
echo "-----";
echo "// "; var_dump($xml); echo " //<br/>";
?><br/><?php
var_dump($xml->gml);
?><br/><?php
print_r($xml);
?><br/><?php
var_dump((string) $xml->gml->featureMember->Hostip->countryName);
?><br/><?php
echo $xml->gml['featureMember']->Hostip->countryName;
$Country = (string) $xml->children('gml', true)
->featureMember->children('', true)
->Hostip->countryName; // => ITALY
echo $Country;
$fm=$xml->xpath('//gml:featureMember');
print_r($fm[0]->Hostip->countryName);
and here are the results output:
BREAK HTML-----// object(SimpleXMLElement)#1 (1) { ["#attributes"]=> array(1) { ["version"]=> string(5) "1.0.1" } } //
object(SimpleXMLElement)#2 (0) { }
SimpleXMLElement Object ( [#attributes] => Array ( [version] => 1.0.1 ) )
string(0) ""
ITALYSimpleXMLElement Object ( [0] => ITALY )
Related
I am making parser of articles and I need to put all parsed data in josn. I tried to put them to array and then transform it in JSON, but I have some troubles. I get JSON like this:
[{"title":"title1"}][{"title":"title2"}][{"title":"title3"}]
But I want like this:
[{"title":"title1"},{"title":"title2"},{"title":"title3"}]
How I can do this?
<?
foreach ($content_prev as $el) {
$pq = pq($el);
$date = $pq->find('time')->html();
$title = $pq->find('h3 a')->html();
$link = $pq->find('h3 a')->attr('href');
$data_link = file_get_contents($link);
$document_с = phpQuery::newDocument($data_link);
$content = $document_с->find('.td-post-content');
$arr = array (
array(
"title" => $title
),
);
echo json_encode($arr, JSON_UNESCAPED_UNICODE);
}
Try to remove one array in $arr
Use below one.
<?
foreach ($content_prev as $el) {
$pq = pq($el);
$date = $pq->find('time')->html();
$title = $pq->find('h3 a')->html();
$link = $pq->find('h3 a')->attr('href');
$data_link = file_get_contents($link);
$document_с = phpQuery::newDocument($data_link);
$content = $document_с->find('.td-post-content');
$arr[] = array (
"title" => $title
);
}
echo json_encode($arr, JSON_UNESCAPED_UNICODE);
I am making a function to download mail data in my DB.Here is my code :
include('simple_html_dom.php');
$html = new simple_html_dom();
global $html;
function getArraySubject($stream,$subject){
$array = imap_search($stream, $subject);
return $array ;
}
// $domain 0 = any domeain from which we are receiving mails
//$case = subject number for ex :- Query, Potential.....
function getDataFromHTML($subjectArray, $domain = 0, $case = 1)
{
$completeArray = array();
if ($domain == 0 && $case == 1) {
rsort($subjectArray);
foreach($subjectArray as $email_id){
$body = imap_qprint(imap_body($stream,$email_id));
$my_file = 'mail-data.txt';
file_put_contents($my_file, $body);
$html = file_get_contents($my_file, true);
$htmlData = $html->str_get_html($body);
$tds = $htmlData->find('table',3)->find('td');
$num = null;
$i = 0 ;
foreach($tds as $td){
$completeArray['magicbricks']['case1'][$i] = $td->innertext;
$i++;
}
}
}
return $completeArray;
}
I am getting an error "Fatal error: Call to a member function str_get_html() on a non-object in line no. 25".
How to resolve this issue? please help.
And this is my second file where I am calling above mentioned function.
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('functions.php');
// Configure your imap mailboxes
$mailboxes = array(
array(
'label' => 'Label',
'mailbox' => '{imap.gmail.com:993/imap/ssl}INBOX',
'username' => 'abc#uabc.com',
'password' => 'abc246'
)
);
foreach ($mailboxes as $current_mailbox) {
// Open an IMAP stream to our mailbox
$stream = #imap_open($current_mailbox['mailbox'], $current_mailbox['username'], $current_mailbox['password']);
if (!$stream) {
?>
<p>Could not connect to: <?php echo $current_mailbox['label']?>. Error: <?php echo imap_last_error()?></p>
<?php
} else {
$sub1 = 'SUBJECT "Query" FROM "magicbricks.com"';
$array1 = getArraySubject($stream,$sub1);
print_r($array1);
if (!count($array1)){
?>
<p>No e-mails found.</p>
<?php
} else {
$result = getDataFromHTML($array1, $domain = 0, $case = 1);
print_r($result);
}
}
// Close our imap stream.
imap_close($stream);
} // end foreach
Most likely $html in this context is a string so you cannot attach any method to it:
$html = file_get_contents($my_file, true); // this is not an instance of simple-html-dom object
$htmlData = $html->str_get_html($body);
^
Remove that:
$htmlData = str_get_html($body); // now this create a simple-html-dom object
include('simple_html_dom.php');
$html = new simple_html_dom();
global $html; //This is unnecessary
function getArraySubject($stream,$subject){
$array = imap_search($stream, $subject);
return $array ;
}
// $domain 0 = any domeain from which we are receiving mails
//$case = subject number for ex :- Query, Potential.....
function getDataFromHTML($subjectArray, $domain = 0, $case = 1)
{
//Add this
global $html;
$completeArray = array();
if ($domain == 0 && $case == 1) {
rsort($subjectArray);
foreach($subjectArray as $email_id){
$body = imap_qprint(imap_body($stream,$email_id));
$my_file = 'mail-data.txt';
file_put_contents($my_file, $body);
$fileData = file_get_contents($my_file, true); //renamed this
$htmlData = $html->str_get_html($body);
$tds = $htmlData->find('table',3)->find('td');
$num = null;
$i = 0 ;
foreach($tds as $td){
$completeArray['magicbricks']['case1'][$i] = $td->innertext;
$i++;
}
}
}
return $completeArray;
}
I have a PHP file (Region.php) and an excerpt of my code is:
<?php
/** Create HTTP POST */
$country = 'Australia';
$area = htmlspecialchars($_POST["area"]);
$seek = '<parameters>
<row><param>COUNTRY</param><value>'. $country .'</value></row>
<row><param>AREA</param><value>'. $area .'</value></row>
</parameters>';
$postdata = http_build_query(
array(
'DistributorKey' => '201201100935',
'CommandName' => 'GetCities',
'CommandParameters' => $seek)
);
$opts = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata)
);
/** Get string output of XML (In URL instance) */
$context = stream_context_create($opts);
$result = file_get_contents('http://national.atdw.com.au/soap/AustralianTourismWebService.asmx/CommandHandler?', false, $context);
/** Change encoding from UTF-16 to Unicode (UTF-8)
Parse unstructured tags */
$result = str_replace('<?xml version="1.0" encoding="utf-8"?>', '', $result);
$result = str_replace('<string xmlns="http://tempuri.org/soap/AustralianTourismWebService">', '', $result);
$result = str_replace('</string>', '', $result);
$result = str_replace('utf-16', 'utf-8', $result);
$result = simplexml_load_string(trim(html_entity_decode($result)), 'SimpleXMLElement');
/** Instantiate Loop */
foreach ($result->area as $entry) {
echo $entry->attributes()->area_name . "<br /><br />";
}
foreach ($result->area->city as $entry) {
$pna = htmlspecialchars_decode($entry->attributes()->suburb_city_postal_code, ENT_QUOTES);
$pna = str_replace("'", "''", $pna);
$str = htmlspecialchars_decode($entry->attributes()->attribute_id_status, ENT_QUOTES);
$str = str_replace("'", "''", $str);
echo $pna. "<br />";
echo $str . "<br />";
echo (string)$entry . "<br /><br />";
}
?>
I have another PHP file (Houses.php) but I need only the value of $entry->attributes()->area_name in the Houses.php file. Excerpt of my code in Houses.php:
<?php
require_once 'Region.php';
/** Create HTTP POST */
$accomm = 'ACCOMM';
$region = '('$entry->attributes()->area_name')';
$page = '10';
---- some code ---
?>
I keep getting errors because it is executes the entire Region.php file whereas I only need the value of the attribute().
Please how can I fix this.
Thanks
I can interpret comments as this, as you cannot include only part of a PHP file:
Create a file header.inc.php, not header.inc for security, as one can download a .inc as source file by bad config, but not .php, as executed by apache2 :
<?php
/** Create HTTP POST */
$country = 'Australia';
$area = htmlspecialchars($_POST["area"]);
$seek = '<parameters>
<row><param>COUNTRY</param><value>'. $country .'</value></row>
<row><param>AREA</param><value>'. $area .'</value></row>
</parameters>';
$postdata = http_build_query(
array(
'DistributorKey' => '201201100935',
'CommandName' => 'GetCities',
'CommandParameters' => $seek)
);
$opts = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata)
);
/** Get string output of XML (In URL instance) */
$context = stream_context_create($opts);
$result = file_get_contents('http://national.atdw.com.au/soap/AustralianTourismWebService.asmx/CommandHandler?', false, $context);
/** Change encoding from UTF-16 to Unicode (UTF-8)
Parse unstructured tags */
$result = str_replace('<?xml version="1.0" encoding="utf-8"?>', '', $result);
$result = str_replace('<string xmlns="http://tempuri.org/soap/AustralianTourismWebService">', '', $result);
$result = str_replace('</string>', '', $result);
$result = str_replace('utf-16', 'utf-8', $result);
$result = simplexml_load_string(trim(html_entity_decode($result)), 'SimpleXMLElement');
?>
Shorten the Region.php file:
<?php
require_once "header.inc.php";
/** Instantiate Loop */
foreach ($result->area as $entry) {
echo $entry->attributes()->area_name . "<br /><br />";
}
foreach ($result->area->city as $entry) {
$pna = htmlspecialchars_decode($entry->attributes()->suburb_city_postal_code, ENT_QUOTES);
$pna = str_replace("'", "''", $pna);
$str = htmlspecialchars_decode($entry->attributes()->attribute_id_status, ENT_QUOTES);
$str = str_replace("'", "''", $str);
echo $pna. "<br />";
echo $str . "<br />";
echo (string)$entry . "<br /><br />";
}
?>
In House.php:
<?php
require_once 'header.inc.php';
/** Create HTTP POST */
$accomm = 'ACCOMM';
$region = "";
foreach ($result->area as $entry) {
$region = $entry->attributes()->area_name;
break;
}
$page = '10';
---- some code ---
?>
All the tree files must reside in the same directory/folder.
Organize your code into functions:
myfuncts.php
function fn1() {
...stuff...
...stuff...
} // fn1()
function fn2() {
...things...
...things...
} // fn2()
Then you can use them by simply calling:
require("functions.php");
fn1();
fn3();
I want to turn the variable into an array so I can store more than one feed?
<?php
error_reporting(0);
$feed_lifehacker_full = simplexml_load_file('http://feeds.gawker.com/lifehacker/full');
$xml = $feed_lifehacker_full;
//print_r($xml);
foreach ($xml->channel->item as $node){
$title = $node->title;
$link = $node->link;
$link = explode('/', $link);
$link = $link[8];
$url = $node->url;
$description = $node->description;
$pubDate = $node->pubDate;
preg_match_all('#(http://img[^\s]+(?=\.(jpe?g|png|gif)))#i', $description[0], $images);
$images = $images[0][1] . '.jpg';
if($images == '.jpg'){
//uncomment to show youtube articles
//$images = "http://placehold.it/640x360";
//echo "<a href='page2.php?a=$link' title='$title'><img src='$images' /></a><br>";
} else {
//article image
$images . '<br>';
echo "<a href='page2.php?a=$link' title='$title'><img src='$images' /></a><br>";
}
}
How can I change this to load to arrays,
$feed_lifehacker_full = simplexml_load_file('http://feeds.gawker.com/lifehacker/full');
$xml = $feed_lifehacker_full;
The script is just gathering the image of an rss feed and linking to a page, if you see how it can be done more efficiently feel free to say
it is possible to encode the result given as json and by decoding it it will return you an array
$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$array = json_decode($json, TRUE);
Essentially, I currently want to parse the XML data that was generated from the html and this was working fine but for some reason will not parse now...gives date of jan 01 1970??...any ideas of problem as coding seems fine?
Thanks a lot in advance!
<?php
//ini_set("disable_functions",null);
//phpinfo();
$string="http://www.thrifty.co.uk/cgi-bin/gen5?runprog=thxml&xsrc=7qhfqou3&mode=quote";
$string.="&xloc=".$_REQUEST["loccode"];
$string.="&xlocname=".$_REQUEST["locname"];
$string.="&xlocdrop=".$_REQUEST["locdrop"];
$string.="&xbook=".$_REQUEST["book"];
$string.="&xonewaystart=".$_REQUEST["onewaystart"];
$string.="&xonewayend=".$_REQUEST["onewayend"];
$string.="&xpuyear=".date("Y",strtotime($_POST['pickup_date']));
$string.="&xpumonth=".date("m",strtotime($_POST['pickup_date']));
$string.="&xpuday=".date("d",strtotime($_POST['pickup_date']));
$string.="&xputime=".$_REQUEST["pu_time"];
$string.="&xdbyear=".date("Y",strtotime($_POST['return_date']));
$string.="&xdbmonth=".date("m",strtotime($_POST['return_date']));
$string.="&xdbday=".date("d",strtotime($_POST['return_date']));
$string.="&xdbtime=".$_REQUEST["db_time"];
$string.="&xclass=".$_REQUEST["vehicle_type"];
echo "<!-- $string -->";
function get_data($url)
{
echo $url;
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
//echo get_data($string);
$xmlDoc=simplexml_load_string ( get_data($string) ) ;
/*
function proxy_url($proxy_url)
{
$proxy_name = '127.0.0.1';
$proxy_port = 4001;
$proxy_cont = '';
$proxy_fp = fsockopen($proxy_name, $proxy_port);
if (!$proxy_fp) {return false;}
fputs($proxy_fp, "GET $proxy_url HTTP/1.0\r\nHost: $proxy_name\r\n\r\n");
while(!feof($proxy_fp)) {$proxy_cont .= fread($proxy_fp,4096);}
fclose($proxy_fp);
$proxy_cont = substr($proxy_cont, strpos($proxy_cont,"\r\n\r\n")+4);
return $proxy_cont;
}
echo proxy_url($string);*/
function XML2Array ( $xml , $recursive = false )
{
if ( ! $recursive )
{
$array = simplexml_load_string ( $xml ) ;
}
else
{
$array = $xml ;
}
$newArray = array () ;
$array = ( array ) $array ;
foreach ( $array as $key => $value )
{
$value = ( array ) $value ;
if ( isset ( $value [ 0 ] ) )
{
$newArray [ $key ] = trim ( $value [ 0 ] ) ;
}
else
{
$newArray [ $key ] = XML2Array ( $value , true ) ;
}
}
return $newArray ;
}
function disp_date($str)
{
$y=substr($str,0,4);
$m=substr($str,4,2);
$d=substr($str,6,2);
//echo $y."-".$m."-".$d;
return date("M d, Y",strtotime($y."-".$m."-".$d));
}
$handle = fgets($string, "r");
$xml_string="";
// If there is something, read and return
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
$xml_string.=$buffer;
}
fclose($handle);
}
//$xmlDoc = new DOMDocument();
//echo "xml string = " . $xml_string;
?></div>
<div class="box">
<?
//print_r($xmlDoc);
echo "<br><strong/>Pick up Location: ".$xmlDoc->hire->loccode."<br> Drop-off Location: ".$xmlDoc->hire->locdrop."<br>Pickup Time: ".disp_date($xmlDoc->hire->pickupdate)." ".$xmlDoc->hire->pickuptime."<br>Dropback Time: ".disp_date($xmlDoc->hire->dropbackdate)." ".$xmlDoc->hire->dropbacktime."<br>";
echo "<table border=1 style='font:12px verdana' cellspacing=0 cellpadding=3><tr><td>Car Type</td><td>Description</td><td>Rate</td></tr>";
foreach($xmlDoc->car as $car)
{
$url = $car->book;
$url = str_replace('wheels4rent.net', '', '$url');
echo "<!-- url = $car->book -->";
echo "<tr><td width=200px><img src='".$car->carimage."' align='left' style='padding:1px; width:100px'><b>".$car->cartype."</b><br>".$car->carsipp."<br>".$car->transmission."</td><td><b>".$car->carexample."</b></td><td><b>£".$car->price."
</b><br>Unlimited Miles</b><br>
<input type=button onclick=\"javascript:newWin('".trim($car->book)."');\" value='Prepay Now'></td></tr>";
}
echo "</table>";
?>
a date of "jan 01 1970" means that the date was either passed in null or as 0 ... check the raw value of your post to make sure it's coming in as expected.
There's a lot of room for improvement on your code but I'll just stick to the problem your reported. My advice would be for you to change your disp_date function to:
function disp_date($str) {
return date("M d, Y", strtotime($str));
}
I just picked up a subset of the XML that URL returns and created this small code snippet for demo purposes:
<?php
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8" ?>
<Quote>
<hire>
<loccode>AI001</loccode>
<locname>LONDON - HEATHROW AIRPORT</locname>
<pickupdate>20130819</pickupdate>
<pickuptime>09:00</pickuptime>
<dropbackdate>20130823</dropbackdate>
<dropbacktime>09:00</dropbacktime>
</hire>
</Quote>
XML;
$sxe = new SimpleXMLElement($xml);
echo date("M d, Y",strtotime($sxe->hire->pickupdate));
Ouptut:
Aug 19, 2013