PHP getElementById not working - php

So I'm trying to write a short function using PHP to check whether a server (or the back up) is available. The service provides two servers to use, and a page within the server that simply has "OK" in an element with id "server_status". I basically took their code that they provided and adjusted it so that it provides the kind of output I need. I want to get an array of true or false (depending on whether one of the sites is available), and the correct page if it is. Right now the output every time is (false, "e404.html"), which is what I set it up to output if no conditions are met. Here is my code:
function checkURL() {
$servers = array('tpeweb.paybox.com', // primary URL
'tpeweb1.paybox.com'); // backup URL
foreach($servers as $server){
$doc = new DOMDocument();
$doc->loadHTMLFile('https://'.$server.'/load.html');
$server_status = "";
$element = $doc->getElementById('server_status');
if($element){
$server_status = $element->textContent;
}
if($server_status == "OK"){
// Server is up and services are available
return array(true, 'https://'.$server.'/cgi/MYchoix_pagepaiement.cgi');
}
}
return array(false, 'e404.html');
}
Doing some output testing, it appears that I'm loading the document into $doc, but it doesn't fill $element. I'm new to PHP so I'm not quite sure what is wrong.
EDIT:
This is the original code that the service provided to make this check, I adjusted it because I needed to be able to actually output the link to use:
<?php
$servers = array('urlserver.paybox.com', // primary URL
'urlserver1.paybox.com'); // backup URL
$serverOK = "";
foreach($servers as $server){
$doc = new DOMDocument();
$doc->loadHTMLFile('https://'.$server.'/load.html');
$server_status = "";
$element = $doc->getElementById('server_status');
if($element){
$server_status = $element->textContent;
}
if($server_status == "OK"){
// Server is up and services are available
$serverOK = $server;
break;
}
// else : Server is up but services are not available .
}
if(!$serverOK){
die("Error : no server found");
}
?>
//echo 'Connecting to https://'.$server.'/cgi/MYchoix_pagepaiement.cgi';
Thanks,
Adrian

Does your html file have a doctype declared?
from http://php.net/manual/en/domdocument.getelementbyid.php
For this function to work, you will need either to set some ID attributes with DOMElement::setIdAttribute or a DTD which defines an attribute to be of type ID.
It should be sufficient to include <!DOCTYPE html> at the very top of your html files, and set
$doc->validateOnParse = true; before calling the getElementByID function.

Related

loadHTMLFile loads, but is empty? PHP

so I tried to get a fix for this earlier but I think we were all going in the wrong direction. I'm trying to check two servers to make sure that at least one of them are active to make a call to. The service provides me with a page for each that simply has "OK" under a div with id="server_status". When I try to loadHTMLFile into a variable, it returns true, but I can never pull the element I need from it. After doing some output testing with saveHTML(), it appears that the variable holding the DOMDocument is empty. Here's my code:
servers = array('tpeweb.paybox.com', // primary URL
'tpeweb1.paybox.com'); // backup URL
foreach($servers as $server){
$doc = new DOMDocument();
$doc->validateOnParse = true;
$doc->loadHTMLFile('https://'.$server.'/load.html');
$server_status = "";
$docText = $doc->saveHTML();
if($doc) {
echo "HTML should output here: ";
echo $docText;
}
if(!$doc) {
echo "HTML file not loaded";
}
$element = $doc->getElementById('server_status');
if($element){
$server_status = $element->textContent;
}
if($server_status == "OK"){
// Server is up and services are available
return array(true, 'https://'.$server.'/cgi/MYchoix_pagepaiement.cgi');
}
}
return array(false, 'e404.html');
All I get as output is "HTML should output here: " twice, and then it returns the array at the bottom. This is the code that they provided:
$servers = array('tpeweb.paybox.com', // primary URL
'tpeweb1.paybox.com'); // backup URL
$serverOK = "";
foreach($servers as $server){
$doc = new DOMDocument();
$doc->loadHTMLFile('https://'.$server.'/load.html');
$server_status = "";
$element = $doc->getElementById('server_status');
if($element){
$server_status = $element->textContent;
}
if($server_status == "OK"){
// Server is up and services are available
$serverOK = $server;
break;
}
// else : Server is up but services are not available .
}
if(!$serverOK){
die("Error : no server found");
}
echo 'Connecting to https://'.$server.'/cgi/MYchoix_pagepaiement.cgi';
This also seems to be having the same problem. Could it be something with my PHP configuration? I'm on version 5.3.6.
Thanks,
Adrian
EDIT:
I tried it by inputting the HTML as a string instead of calling it to the server and it worked fine. However, calling the HTML into a string to use in the PHP function results in the same issue. Fixes??

How to fix XML-RPC Client returning fault code in PHP?

It is my first experience with XML-RPC. I am having a problem retrieving the data from the server as it's being returned to client as fault code. Why is this happening? Do I also need to make an XML-RPC Server file or is it already set up here?
$beerClient = new xmlrpc_client('localhost:1234/341/xmlrpc-lab/xmlrpcserver.php','alvin.ist.rit.edu:8100',1234);
Is it because the data does not match the server return type or something else I'm missing?
I made sure I included the xmlrpc libraries to the right path and everything.
The webpage error returns:
An XML-RPC Fault Occured
Fault Code:-1
Fault Desc:java.lang.NoSuchMethodException: BeerHandler.List()
XML-RPC Client:
<?php
require_once('xmlrpc-3.0.0.beta/lib/xmlrpc.inc');
// Initialize $Beers as an empty Array.
// $Beers will hold all the information available for each beer.
// (BeerID, Name, Rating, Comments)
//
// It will be used later to create the HTML output.
$Beers = Array();
// GET A LIST OF THE AVAILABLE BEERS ON THE XML-RPC SERVER
$beerClient = new xmlrpc_client('localhost:1234/341/xmlrpc-lab/xmlrpcserver.php','alvin.ist.rit.edu:8100',1234);
$msg_listBeers = new xmlrpcmsg('beer.List');
$response = $beerClient->send($msg_listBeers);
if($response == false)
{
die('Unable to contact XML-RPC Server');
}
if(!$response->faultCode()) // faults occurred?
{
// convert to a more usable PHP Array
$beerList = xmlrpc_decode($response->value());
foreach($beerList as $beerID => $beerName)
{
// for each available beer listed by the server grab it's
// a) Rating
// b) Comments
//
// and put the data into the $Beer array. This is incredibly
// inefficient since it performs a lot of HTTP calls to grab each
// piece of data. Not recommended for use beyond this example.
$Beers[$beerID]['name'] = $beerName;
// GET THE RATING FOR THE CURRENT BEER
// Build XML-RPC Request for the Beer's Rating
$msg_beerRating = new xmlrpcmsg('beer.Rating',array(new xmlrpcval($beerID, 'int')));
// Send the Message to the server
$response = $beerClient->send($msg_beerRating);
// Negative number If no rating found
$Beers[$beerID]['rating'] = (!$response->faultCode()) ? xmlrpc_decode($response->value()) : -1;
// GET THE COMMENTS FOR THE CURRENT BEER
$msg_beerComments = new xmlrpcmsg('beer.Comments', array(new xmlrpcval($beerID,'int')));
// Send the Message to the server
$response = $beerClient->send($msg_beerComments);
// Fill in the Comments for the Beer
$Beers[$beerID]['comments'] = (!$response->faultCode()) ? xmlrpc_decode($response->value()) : array(); //empty array for not Comments
} // END foreach ($beerList as ...
}
else // XML-RPC returned a fault...
{
echo '<h1>An XML-RPC Fault Occured</h1>';
printf('<b>Fault Code:</b>%s<br/>',$response->faultCode());
printf('<b>Fault Desc:</b>%s<br/>',$response->faultString());
die();
}
// GENERATE THE OUTPUT
$xmlrpc_client->setDebug(1); // turn on debugging, if I/O fault occurred between communication xmlrpc_client and xmlrpc_server
?>
<html>
<head>
<title>Beer List XML-RPC</title>
<meta charset="utf-8">
</head>
<body>
<h1>Beer List</h1>
<ol type="1">
<?php
if(count($Beers))
{
foreach($Beers as $BeerData)
{
printf('<font size="+2" color="#990000"><li> %s</font><br>', $BeerData['beer']);
// Output the beer's rating if it exists
if($BeerData['rating'] != -1)
{
printf('<b>Rating: %s/5.0</b><br>',$BeerData['rating']);
}
// Output the beer's comments if they exist
if(count($BeerData['comments']))
{
echo '<b>Comments:</b><ul>';
foreach($BeerData['comments'] as $Comment)
{
echo "<li> $Comment";
}
echo '</ul>';
}
}
}
else
{
echo '<li> Darn No Beers Found';
}
?>
</ol>
</body>
</html>

Handle errors in simple html dom

I have some code to get some public available data that i am fetching from a website
//Array of params
foreach($params as $par){
$html = file_get_html('WEBSITE.COM/$par');
$name = $html->find('div[class=name]');
$link = $html->find('div[class=secondName]');
foreach($link as $i => $result2)
{
$var = $name[$i]->plaintext;
echo $result2->href,"<br>";
//Insert to database
}
}
So it goes to the given website with a different parameter in the URL each time on the loop, i keep getting errors that breaks the script when a 404 comes up or a server temporarily unavailable. I have tried code to check the headers and check if the $html is an object first but i still get the errors, is there a way i can just skip the errors and leave them out and carry on with the script?
Code i have tried to checked headers
function url_exists($url){
if ((strpos($url, "http")) === false) $url = "http://" . $url;
$headers = #get_headers($url);
//print_r($headers);
if (is_array($headers)){
//Check for http error here....should add checks for other errors too...
if(strpos($headers[0], '404 Not Found'))
return false;
else
return true;
}
else
return false;
}
Code i have tried to check if object
if (method_exists($html,"find")) {
// then check if the html element exists to avoid trying to parse non-html
if ($html->find('html')) {
// and only then start searching (and manipulating) the dom
You need to be more specific, what kind of errors are you getting? Which line errors out?
Edit: Since you did specify the errors you're getting, here's what to do:
I've noticed you're using SINGLE quotes with a string that contains variables. This won't work, use double quotes instead, i.e.:
$html = file_get_html("WEBSITE.COM/$par");
Perhaps this is the issue?
Also, you could use file_get_contents()
if (file_get_contents("WEBSITE.COM/$par") !== false) {
...
}

Save XML retrieved with rest and php

I can retrieve certain information with a rest command, the data it shows (in the browser) is already an XML. How do I save it to an XML file on the server after retrieving the information.
I have already tried it with the $dom-save command but I seem to do something wrong. Any help would be appreciated. See below for code (I want to save the $response to XML.)
<?php
require_once 'includes/rest_connector.php';
require_once 'includes/session.php';
// check to see if we start a new session or maintain the current one
checksession();
$rest = new RESTConnector();
$url = "/api/tax_codes/0/";
$rest->createRequest($url,"GET", null, $_SESSION['cookies'][0]);
$rest->sendRequest();
$response = $rest->getResponse();
$error = $rest->getException();
// save our session cookies
if ($_SESSION['cookies']==null)
$_SESSION['cookies'] = $rest->getCookies();
// display any error message
if ($error!=null)
echo $error;
// display the response
if ($response!=null)
echo $response;
else
echo "There was no response.";
?>
The RESTConneconnector is a specific class Lightspeed. I solved it by using this:
ibxml_use_internal_errors(true);//load if improperly formatted
file_put_contents("exportProduct.xml", $responseProduct);
So it was very easy in the end :)
I dont know any about RESTConnector class. But I suppose, you can try something like it:
$dom = new DOMDocument('1.0','utf-8');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($response->asXML());
$dom->save($this->fileexport);

Having trouble getting the right idea

well i'm writing a php code to edit tags and data inside those tags but i'm having big trouble getting my head around the thing.
basically i have an xml file similar to this but bigger
<users>
<user1>
<password></password>
</user1>
</users>
and the php code i'm using to try and change the user1 tag is this
function mod_user() {
// Get global Variables
global $access_level;
// Pull the data from the form
$entered_new_username = $_POST['mod_user_new_username'];
$entered_pass = $_POST['mod_user_new_password'];
$entered_confirm_pass = $_POST['mod_user_confirm_new_password'];
$entered_new_roll = $_POST['mod_user_new_roll'];
$entered_new_access_level = $_POST['mod_user_new_access_level'];
// Grab the old username from the last page as well so we know who we are looking for
$current_username = $_POST['mod_user_old_username'];
// !!-------- First thing is first. we need to run checks to make sure that this operation can be completed ----------------!!
// Check to see if the user exist. we just use the normal phaser since we are only reading and it's much easier to make loop through
$xml = simplexml_load_file('../users/users.xml');
// read the xml file find the user to be modified
foreach ($xml->children() as $xml_user_get)
{
$xml_user = ($xml_user_get->getName());
if ($xml_user == $entered_new_username){
// Set array to send data back
//$a = array ("error"=>103, "entered_user"=>$new_user, "entered_roll"=>$new_roll, "entered_access"=>$new_access_level);
// Add to session to be sent back to other page
// $_SESSION['add_error'] = $a;
die("Username Already exist - Pass");
// header('location: ../admin.php?page=usermanage&task=adduser');
}
}
// Check the passwords and make sure they match
if ($entered_pass == $entered_confirm_pass) {
// Encrypt the new password and unset the old password variables so they don't stay in memory un-encrytped
$new_password = hash('sha512', $entered_pass);
unset ($entered_pass, $entered_confirm_pass, $_POST['mod_user_new_password'], $_POST['mod_user_confirm_pass']);
}
else {
die("passwords did not match - Pass");
}
if ($entered_new_access_level != "") {
if ($entered_new_access_level < $access_level){
die("Access level is not sufficiant to grant access - Pass");
}
}
// Now to load up the xml file and commit changes.
$doc = new DOMDocument;
$doc->formatOutput = true;
$doc->perserveWhiteSpace = false;
$doc->load('../users/users.xml');
$old_user = $doc->getElementsByTagName('users')->item(0)->getElementsByTagName($current_username)->item(0);
// For initial debugging - to be deleted
if ($old_user == $current_username)
echo "old username found and matches";
// Check the variables to see if there is something to change in the data.
if ($entered_new_username != "") {
$xml_old_user = $doc->getElementsByTagName('users')->item(0)->getElementsByTagName($current_username)->item(0)->replaceChild($entered_new_username, $old_user);
echo "Username is now: " . $current_username;
}
if ($new_pass != "") {
$current_password = $doc->getElementsByTagName($current_user)->item(0)->getElementsByTagName('password')->item(0)->nodeValue;
//$replace_password = $doc
}
}
when run with just the username entered for change i get this error
Catchable fatal error: Argument 1 passed to DOMNode::replaceChild() must be an instance of DOMNode, string given, called in E:\xampp\htdocs\CGS-Intranet\admin\html\useraction.php on line 252 and defined in E:\xampp\htdocs\CGS-Intranet\admin\html\useraction.php on line 201
could someone explain to me how to do this or show me how they'd do it.. it might make a little sense to me to see how it's done :s
thanks
$entered_new_username is a string so you'll need to wrap it with a DOM object, via something like$doc->createElement()
$xml_old_user = $doc->getElementsByTagName('users')->item(0)->getElementsByTagName($current_username)->item(0)->replaceChild($doc->createElement($entered_new_username), $old_user);
This may not be quite right, but hopefully it points you in the correct direction.
alright got it writing and replacing the node that i want but i have ran into other issues i have to work out (IE: it's replacing the whole tree rather then just changing the node name)
anyway the code i used is
// For initial debugging - to be deleted
if ($old_user == $current_username)
echo "old username found and matches";
// Check the variables to see if there is something to change in the data.
if ($entered_new_username != "") {
try {
$new_node_name = $doc->createElement($entered_new_username);
$old_user->parentNode->replaceChild($new_node_name, $old_user);
}
catch (DOMException $e) {
echo $e;
}
echo "Username is now: " . $current_username;
}
if ($new_pass != "") {
$current_password = $doc->getElementsByTagName($current_user)->item(0)->getElementsByTagName('password')->item(0)->nodeValue;
//$replace_password = $doc
}
$doc->save('../users/users.xml');

Categories