【php】利用新浪api接口与php获取远程数据的方法,获取IP地址,并获取相应的IP归属地
本文与《【Servlet】Javaweb中,利用新浪api接口,获取IP地址,并获取相应的IP归属地》(点击打开链接)为姊妹篇,只是后端编程语言换成了php。
做出同样的效果,打开页面,得到客户端的ip,并获取利用新浪api接口获取此ip的归属地。
可以看到,在IE6也是相当正常的。
目录结构如下,非常简单,同样就两个文件,其实如果你愿意,写成一个php文件也可以,但是显示层和逻辑业务层还是不混在一起为好吧?
唯一值得注意的是,这两个文件打死也不能一个叫ipGet.php,ipGet.html,虽然后缀名是不同的,但前缀一定不能相同,
否则IE6不知为何无法应答这个Json
ipGetView.html与《【Servlet】Javaweb中,利用新浪api接口,获取IP地址,并获取相应的IP归属地》(点击打开链接)中的显示层页面是完全相同,新浪api接口也是完全相同的,这里不再赘述。
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Javaweb-IP查询</title> <p>IP:<span id="ip"></span></p> <p>IP归属地:<span id="area"></span></p><script> //创建Ajax对象,不同浏览器有不同的创建方法,其实本函数就是一个简单的new语句而已。 function createXMLHttpRequest() { var XMLHttpRequest1; if (window.XMLHttpRequest) { XMLHttpRequest1 = new XMLHttpRequest(); } else if (window.ActiveXObject) { try { XMLHttpRequest1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { XMLHttpRequest1 = new ActiveXObject("Microsoft.XMLHTTP"); } } return XMLHttpRequest1; } function ajax() { var XMLHttpRequest1 = createXMLHttpRequest(); //指明相应页面 var url = "ipGetDo.php"; XMLHttpRequest1.open("POST", url, true); //这里没法解释,你所有JavaScript的请求头都这样写就对了,不会乱码 XMLHttpRequest1.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); XMLHttpRequest1.send(null); //对于返回结果怎么处理的问题 XMLHttpRequest1.onreadystatechange = function() { //这个4代表已经发送完毕之后 if (XMLHttpRequest1.readyState == 4) { //200代表正确收到了返回结果 if (XMLHttpRequest1.status == 200) { //json返回结果 var data=eval("("+XMLHttpRequest1.responseText+")"); document.getElementById("ip").innerHTML=data.ip; document.getElementById("area").innerHTML=decodeURIComponent(data.area1)+decodeURIComponent(data.area2); } else { //如果不能正常接受结果,你肯定是断网,或者我的服务器关掉了。 alert("网络连接中断!"); } } }; } ajax();</script>之后,ipGetDo.php中,如同《【php】登录系统与输出浏览者信息》(点击打开链接)一样,利用${_SERVER['REMOTE_ADDR']}先获取用户的ip,然后通过curl向远程获取数据。php用curl向远程获取数据的格式如下:
<?php $url = "需要获取数据的url"; $ch = curl_init(); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10); $DistanceContent = curl_exec($ch); echo $DistanceContent; //$DistanceContent为获取到的数据?>
因此ipGetDo.php的代码也就如下,获取到数据,直接打印出来,让ipGetView.html用Ajax获取即可。
<?php $url = "http://ipapi.sinaapp.com/api.php?f=json&ip=${_SERVER['REMOTE_ADDR']}"; $ch = curl_init(); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10); $DistanceContent = curl_exec($ch); echo $DistanceContent; ?>

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
