Am dynamically loading an xml file and sending request to the api but getting
Warning: DOMDocument::loadXML(): Empty string supplied as input in /home/spotrech/public_html/ but this error is very inconsistent sometime appear sometime don't! I really no idea how to solve this. below is code
$rechargeApiUrl = "http://allrechargeapi.com/apirecharge.ashx?uid=$uid&apikey=$apike&number=$mobileNo&opcode=$opId&amount=$amount&ukey=$uniId&format=xml";
$url = file_get_contents($rechargeApiUrl);
$xmlDoc = new DOMDocument();
$xmlDoc->loadXML(preg_replace('/(<\?xml[^?]+?)utf-16/i', '$1utf-8', $url));
$itemInfo = $xmlDoc->getElementsByTagName('Result'); //returns an object.
$itemCount = $itemInfo->length;
foreach ($itemInfo as $userInfo) {
//Assigning node values to its specified variables.
$ukey = strtolower($userInfo->getElementsByTagName('ukey')->item(0)->childNodes->item(0)->nodeValue);
$status = $userInfo->getElementsByTagName('status')->item(0)->childNodes->item(0)->nodeValue;
$resultCode = $userInfo->getElementsByTagName('resultcode')->item(0)->childNodes->item(0)->nodeValue;
}
$strStatus = strtolower(trim($status));
$strResultCode = trim($resultCode);
$strCode = trim($ukey);
any response will be appreciated.Thank you
Related
I am trying to understand the new stdClass in terms of sending data to a function, I've created the following code and I'll get an error that's saying Warning: Creating default object from empty value, however, still I get the json data as well. How to fix the error and why I am getting it?
$send = new stdClass();
$send->user->id = '12121212121';
$send->message->attachment->type = 'file';
$send->message->attachment->image = 'png';
$res = process($send);
function process($send){
$data = json_encode($send);
print_r($data);
}
Result is looks like this and there is an error above below result as I mentioned it:
{"user":{"id":"12121212121"},"message":{"attachment":{"type":"file","image":"png"}}}
Create stdClass for each reference like this
$send = new stdClass();
$send->user=new stdClass();
$send->user->id = '12121212121';
$send->message=new stdClass();
$send->message->attachment=new stdClass();
$send->message->attachment->type = 'file';
$send->message->attachment->image = 'png';
$res = process($send);
function process($send){
$data = json_encode($send);
print_r($data);
}
I had this line of code which was working fine until I update the php version of my server from 5.3 to 5.6.
It re-writes a xml file.
I guess this line is not compactible with 5.6, but I don't know what is wrong exactly:
$newXml->asXml('my_xml.xml');
And this is the error message:
Fatal error: Call to a member function asXml() on boolean in /usr/home/example/www/sites/all/modules/custom/inmovilla_rewrite/inmovilla_rewrite.module on line 71
What changes should I do here?
UPDATE Complete function
<?php
/**
* Implemetns hook_cron()
*/
function inmovilla_rewrite_cron() {
$xml_external_path = 'http://ap.apinmo.com/portal/mls/jamp623433/my_xml.xml';
$xml = file_get_contents($xml_external_path);
$pattern = '/<unico>(.*?)<\/unico>/';
$response = preg_replace_callback($pattern,function($match){
$valueUnico = trim($match[1]);
$valueUnico = substr($valueUnico, 0, -4);
return '<unico>'.$valueUnico.'</unico>';
},$xml);
$searches = array();
$replacements = array();
for ($i = 1; $i <= 30; $i++) {
$searches[] = 'foto'.$i.'>';
$replacements[] = 'foto1>';
}
$response = str_replace( $searches, $replacements, $response ) ;
$newXml = $response;
$newXml = simplexml_load_string( $newXml );
$newXml->asXml('my_xml.xml');
}
You are calling the method: asXml() on a boolean data-type, not an instance of SimpleXMLElement - you are presumably not feeding in a "well-formed" XML string.
See here: http://php.net/manual/en/function.simplexml-load-string.php
Returns an object of class SimpleXMLElement with properties containing the data held within the xml document, or FALSE on failure.
You should firstly implement some error checking rather than assume that you have a SimpleXMLElement instance, e.g.
$newXml = simplexml_load_string($newXml);
if ($newXml instanceof SimpleXMLElement) {
$xml = $newXml->asXml('my_xml.xml');
}
However, you will need to do some further debugging on the values held in $newXml / $response to see what is wrong with the XML string. I cannot see the XML contents in your question to advise any further as to why the change of PHP version has affected this.
OK... I am using PHP 5 (be gentle, still learning PHP). CURL is enabled. Attempting to load XML or JSON output from an API to an object and nothing happens. When I manually execute the URL in question, I get what I am expecting.
Here is my code:
class XmlToJson {
public function Parse ($url) {
$fileContents = file_get_contents($url);
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
$simpleXml = simplexml_load_string($fileContents);
$json = json_encode($simpleXml);
return $json;
}
}
$_MySQLServer = "localhost";
$_MySQLServerUserName = "";
$_MySQLServerPassword = "";
$_MySQLDatabaseName = "";
$_SSActiveWear_UserID = "*****";
$_SSActiveWear_APIKey = "*****";
$_SSActiveWear_APIBaseURL = "https://*****/v2";
$_CategoryURL = "/categories/";
$_StylesURL = "/styles/";
$_ProductsURL = "/products/";
$_SpecsURL = "/specs/";
$_SSActiveWear_MediaType = "xml";
//$_conn = mysqli_connect($_MySQLServer, $_MySQLServerUserName, $_MySQLServerPassword, $_MySQLDatabaseName);
//Insert or Update Categories
$_URL = $_SSActiveWear_APIBaseURL . $_CategoryURL;
$_URL = $_URL . "?mediatype=$_SSActiveWear_MediaType&UserName=$_SSActiveWear_UserID&Password=$_SSActiveWear_APIKey";
$OBJ = simplexml_load_string($_URL);
print_r($OBJ);
What am I doing wrong?
Edit 1
Added the following code:
$xml = simplexml_load_file($_URL) or die("Error: Cannot create object");
print_r($xml);
and it dies. Does that mean that there is something wrong with the code?
Try this :
$OBJ = simplexml_load_string(file_get_contents($_URL));
If you want to know why your code is not working, you are trying to load XML from URL but "simplexml_load_string" loads XML from string.
I FINALLY figured it out... More to the point I finally found a site on Google that helped. It is the first answer in fsockopen with http authentication problem.
So here is the code that works:
file_get_contents("https://$_SSActiveWear_UserID:$_SSActiveWear_APIKey#$_SSActiveWear_APIBaseURL$_CategoryURL/?mediatype=$_SSActiveWear_MediaType");
mediatype can be either json or xml
Driving me bonkers- I've got a simple XML element, and I just want to extract the '_Code' attribute. How would I do it?
<?php
$responseCode = "<STATUS _Condition='FAILURE' _Code='0705' _Description='Search failed subject not found' />";
$xml = simplexml_load_string($responseCode);
print_r($xml);
$code = $xml=>#attributes=>_Code; // Parse error
$code = $xml['#attributes']['_Code']; // Returns blank
echo "CODE = ".(string)$code;
?>
CODE =
http://php.net/manual/en/function.simplexml-load-string.php
Use SimpleXMLElement::attributes()
$attrs = $xml->attributes();
$code = $attrs['_Code'];
I'm using the following code to turn user's IP into latitude/longitude information using the hostip web service:
//get user's location
$ip=$_SERVER['REMOTE_ADDR'];
function get_location($ip) {
$content = file_get_contents('http://api.hostip.info/?ip='.$ip);
if ($content != FALSE) {
$xml = new SimpleXmlElement($content);
$coordinates = $xml->children('gml', TRUE)->featureMember->children('', TRUE)->Hostip->ipLocation->children('gml', TRUE)->pointProperty->Point->coordinates;
$longlat = explode(',', $coordinates);
$location['longitude'] = $longlat[0];
$location['latitude'] = $longlat[1];
$location['citystate'] = '==>'.$xml->children('gml', TRUE)->featureMember->children('', TRUE)->Hostip->children('gml', TRUE)->name;
$location['country'] = '==>'.$xml->children('gml', TRUE)->featureMember->children('', TRUE)->Hostip->countryName;
return $location;
}
else return false;
}
$data = get_location($ip);
$center_long=$data['latitude'];
$center_lat=$data['longitude'];
This works fine for me, using $center_long and $center_lat the google map on the page is centered around my city, but I have a friend in Thailand who tested it from there, and he got this error:
Warning: get_location() [function.get-location]: Node no longer exists in /home/bedbugs/registry/index.php on line 21
So I'm completely confused by this, how could he be getting an error if I don't? I tried googling it and it has something to do with parsing XML data, but the parsing process is the same for me and him. Note that line 21 is the one that starts with '$coordinates =' .
You need to check the service actually has an <ipLocation> listed, you're doing:
$xml->children('gml', TRUE)->featureMember->children('', TRUE)->Hostip->ipLocation
->children('gml', TRUE)->pointProperty->Point->coordinates
but the XML output for my IP is:
<HostipLookupResultSet version="1.0.1" xsi:noNamespaceSchemaLocation="http://www.hostip.info/api/hostip-1.0.1.xsd">
<gml:description>This is the Hostip Lookup Service</gml:description>
<gml:name>hostip</gml:name>
<gml:boundedBy>
<gml:Null>inapplicable</gml:Null>
</gml:boundedBy>
<gml:featureMember>
<Hostip>
<ip>...</ip>
<gml:name>(Unknown City?)</gml:name>
<countryName>(Unknown Country?)</countryName>
<countryAbbrev>XX</countryAbbrev>
<!-- Co-ordinates are unavailable -->
</Hostip>
</gml:featureMember>
</HostipLookupResultSet>
The last part ->children('gml', TRUE)->pointProperty->Point->coordinates gives the error because it has no children (for some IPs).
You can add a basic check to see if the <ipLocation> node exists like this (assuming the service always returns at least up to the <hostIp> node):
function get_location($ip) {
$content = file_get_contents('http://api.hostip.info/?ip='.$ip);
if ($content === FALSE) return false;
$location = array('latitude' => 'unknown', 'longitude' => 'unknown');
$xml = new SimpleXmlElement($content);
$hostIpNode = $xml->children('gml', TRUE)->featureMember->children('', TRUE)->Hostip;
if ($hostIpNode->ipLocation) {
$coordinates = $hostIpNode->ipLocation->children('gml', TRUE)->pointProperty->Point->coordinates;
$longlat = explode(',', $coordinates);
$location['longitude'] = $longlat[0];
$location['latitude'] = $longlat[1];
}
$location['citystate'] = '==>'.$hostIpNode->children('gml', TRUE)->name;
$location['country'] = '==>'.$hostIpNode->countryName;
return $location;
}