Im trying to get the text out xpath/html using php..but not successful any idea.
Example:
https://safeweb.norton.com/report/show?url=google.com
My xpath (This is correct i already double check)
//*[#id="bodyContent"]/div/div/div[3]/div[1]/div[1]/div[2]/div[1]/div/b
I want to get a result to appear here <div> result </div> using php
Below is my code:
<?php
public function getNortonSafe($domain)
{
try
{
$callback_url = "https://safeweb.norton.com/report/show?url=google.com"; //. $domain;
$curl_response = $this->curl->get($callback_url);
if ($curl_response->headers['Status-Code'] == "200") {
libxml_use_internal_errors(TRUE);
$this->dom_doc->loadHTML($curl_response);
libxml_use_internal_errors(FALSE);
$xpath = new DOMXPath($this->dom_doc);
$tmp = $xpath->query('//*[#id="bodyContent"]/div/div/div[3]/div[1]/div[1]/div[2]/div[1]/div/b')->item(0)->textContent);
$tmp = explode(' ', trim($tmp));
$norton_site_test = str_replace(",", "", $tmp[0]);
} else {
$norton_site_test = "0";
}
$response = array(
'status' => 'success',
'data' => array(
'norton_site_test' => filter_var($norton_site_test, FILTER_SANITIZE_STRING)
)
);
}
catch (Exception $e)
{
$response = array(
'status' => 'error',
'msg' => $e->getMessage()
);
}
return $response;
}
?>
HTML
<body>
<p id="norton_site_test"> result-text-here </p>
</body>
When executing the $xpath->query('some xpath here')->text(0) line an error occurs: Fatal error: Call to undefined method DOMNodeList::text(). Please check your PHP error reporting settings.
DOMXPath::query method returns DOMNodeList object that has only item method (see DOMNodeList).
You need to call:
$xpath->query('some xpath here')->item(0)->textContent
to get the text content of the first node from the received DOMNodeList object.
Just an Update regarding this code, and thank you to #camelsWrite - its working Now! with this clean code and tested:
public function getNortonSafe($domain)
{
try
{
$callback_url = "https://safeweb.norton.com/report/show?url= . $domain; //e.g $url: "https://safeweb.norton.com/report/show?url=google.com
$curl_response = $this->curl->get($callback_url);
if ($curl_response->headers['Status-Code'] == "200") {
libxml_use_internal_errors(TRUE);
$this->dom_doc->loadHTML($curl_response);
libxml_use_internal_errors(FALSE);
$xpath = new DOMXPath($this->dom_doc);
$tmp = $xpath->query('//*[#id="bodyContent"]/div/div/div[3]/div[1]/div[1]/div[2]/div[1]/div/b')->item(0)->textContent);
$tmp = explode(' ', trim($tmp));
$norton_site_test = str_replace(",", "", $tmp[0]);
} else {
$norton_site_test = "0";
}
$response = array(
'status' => 'success',
'data' => array(
'norton_site_test' => filter_var($norton_site_test)
)
);
}
catch (Exception $e)
{
$response = array(
'status' => 'error',
'msg' => $e->getMessage()
);
}
return $response;
} ?>
Related
I have a big numbers from Products in Magneto and i must add EAN Numbers to all the Products.
How could i update the new attribute from the CSV file through API.i want to update the EAN numbers from a ssh server through API SOAP.
This is not a full solution for you, but it is definitely a starting point for you. Good Luck
$productData = array(
'additional_attributes' => array(
'single_data' => array(
array(
'key' => 'ean',
'value' => 'value',
),
),
),
);
$productId = '1000000';
$soap = new SoapConnection('1','2','3');
echo $soap->_catalogProductUpdate($productId,$productData);
class SoapConnection
{
protected $soap_client;
protected $session_id;
function __construct($soap_host, $api_user, $api_pass)
{
try{
echo "Connecting to $soap_host\n";
$this->soap_client = new SoapClient( $soap_host, array('trace' =>true,
'connection_timeout' => 30,
'cache_wsdl' => WSDL_CACHE_NONE,
'keep_alive' => false
));
$this->session_id = $this->soap_client->login( $api_user, $api_pass);
echo "Connected with session id ".$this->session_id."\n";
return true;
} catch (SoapFault $e) {
echo "Soap Exception connecting to $soap_host: ". $e->getMessage(). "\n";
var_dump($this->soap_client->__getLastRequest()); var_dump($this->soap_client->__getLastResponse());
return false;
}
}
function _catalogProductUpdate($sku, $args)
{
try
{
return $this->soap_client->catalogProductUpdate($this->session_id, $sku, $args);
} catch (SoapFault $e) {
echo "Soap Exception _catalogProductUpdate: ". $e->getMessage(). "\n";
return false;
}
}
}
EDIT:
here is how to read a csv:
$file = fopen("my file path .csv","r");
while($row = fgetcsv($file))
{
$row[0];//column1
$row[1];//column2 etc etc etc
}
fclose($file);
Updating my collection record field with 'MongoBinData', exception is triggered:
"document fragment is too large: 21216456, max: 16777216"
I find some web discussion about 'allowDiskUse:true' for aggregate, but nothing ubout 'update'.
Here a part of code in PHP:
try {
$criteria = array( '_id' => $intReleaseId);
$fileData = file_get_contents( $_FILES[ $fileKey]["tmp_name"]);
$mongoBinData = new MongoBinData( $fileData, MongoBinData::GENERIC)
$docItem['data'] = $mongoBinData;
$docItem['fileType'] = $strFileType;
$docItem['fileSize'] = $intFileSize;
$docItem['fileExtension'] = $strFileExtension;
$docItem['fileName'] = $strFileName;
$options = array( "upsert" => true,
'safe' => true, 'fsync' => true,
'allowDiskUse' => true ); // this option doesn't change anything
$reportJson = self::GetCollection('releases')->update( $criteria, $docItem, $options);
...
MongoDb release is db version v3.0.6
Some idea ?
Self resolved.
Use gridFS is immediate and simple.
$_mongo = new MongoClient();
$_db = $_mongo->selectDB($_mDbName);
$_gridFS = $_db->getGridFS();
/* */
function saveFileData($intReleaseId, $binData) {
$criteria = array( '_id' => $intReleaseId);
// if exist or not, remove previous value
try {
$_gridFS->remove( $criteria);
}
catch(Exception $e) {}
// store new file content
$storeByteCompleted = false;
try {
$reportId = $_gridFS->storeBytes(
$binData,
array("_id" => $intReleaseId));
if ($reportId == $intReleaseId) {
$storeByteCompleted = true;
}
catch(Exception $e) {}
return $storeByteCompleted;
}
function loadFileData($intReleaseId) {
$gridfsFile = null;
$binData = null;
try {
$gridfsFile = $_gridFS->get($intReleaseId);
}
catch(Exception $e) {}
if ($gridfsFile != null) {
$binData = $gridfsFile->getBytes()
}
return $binData;
}
That's all.
What my problem is that I can not send array to solr machine in order to update. I am using codeigniter as a framework and here is my code:
$solrData = array();
$solrData['id'] = $this->data['profil_data']['id'];
$solrData['site'] = $this->data['profil_data']['site'];
$solrData['url_Domain'] = $this->data['profil_data']['url_Domain'];
$solrData['url_Page'] = $this->data['profil_data']['url_Page'];
$solrData['url_Profil'] = $this->data['profil_data']['url_Profil'];
$solrData['scr_Kobi_Rank'] = $this->data['profil_data']['scr_Kobi_Rank'];
$solrData['scr_A'] = $this->data['profil_data']['scr_A'];
$solrData['scr_B'] = $this->data['profil_data']['scr_B'];
$solrData['scr_C'] = $this->data['profil_data']['scr_C'];
$solrData['scr_D'] = $this->data['profil_data']['scr_D'];
$solrData['loc_City'] = $this->input->post('plakano');
$solrData['loc_Lat_Lon'] = $this->input->post('loc_Lat_Lon');
$solrData['com_Category'] = explode(',', $this->input->post('category'));
$urunData = $this->input->post('urun_list');
foreach($urunData as $row)
{
$ontoData = $this->m_onto->getOntoDataByOntoDataId($row);
$solrData['com_Products'][] = $ontoData['baslik'];
}
$hizmetData = $this->input->post('hizmet_list');
foreach($hizmetData as $row)
{
$ontoData = $this->m_onto->getOntoDataByOntoDataId($row);
$solrData['com_Services'][] = $ontoData['baslik'];
}
$solrData['com_Type'] = $this->input->post('sirketturu');
$solrData['com_Description'] = $this->input->post('description');
$solrData['com_Title_Selected'] = $this->input->post('title');
$solrData['com_Title_Long'] = $this->data['profil_data']['com_Title_Long'];
$solrData['crm_Tel'] = $this->input->post('tel');
$solrData['crm_Fax'] = $this->input->post('fax');
$solrData['crm_Email'] = $this->input->post('email');
$this->solr->updateSolrProfilData($solrData);
And solr process:
public function updateSolrProfilData($arrData)
{
if(count($arrData) == 0)
return FALSE;
$solrClientOptions = $this->solrClientOptionsYazProfil;
$solrClientOptionsCommit = $this->solrClientOptionsYazProfilCommit;
$solrClient = new SolrClient($solrClientOptions);
$solrDoc = new SolrInputDocument();
foreach($arrData as $firmaField => $firmaValue)
{
if(! is_array($firmaValue))
{
$solrDoc->addField($firmaField, $firmaValue);
}
else
{
foreach($firmaValue as $firmaField2 => $firmaValue2)
{
if($firmaValue2 != '')
{
$solrDoc->addField($firmaField, $firmaValue2);
}
}
}
}
try {
$this->_solrCommit($solrClientOptionsCommit);
} catch (Exception $e) {
echo $e->getMessage();
}
}
Solr Commit function:
private function _solrCommit($solrArr)
{
$urlCommit = 'http://' . $solrArr['hostname'] . ":" . $solrArr['port'] . '/' . $solrArr['path'] . "/update?stream.body=%3Ccommit/%3E&wt=json";
$output = file_get_contents($urlCommit);
$outputArr = json_decode($output, TRUE);
if ($outputArr['responseHeader']['status'] === 0)
return TRUE;
else
return FALSE;
}
And that is the options:
private $solrClientOptionsYazProfilCommit = array(
'hostname' => SOLR_HOST_YAZ,
'login' => '',
'password' => '',
'port' => SOLR_PORT,
'path' => 'solr/collection1'
);
Altough try-catch returns no error, the data can not be updated. Moreover, code sends solr commit succesfully. I checked the url but it is in correct form. What is wrong in here?
Dont use PHP/Pecl solr libs. If you can access solr via a URL then you should just use PHP and CURL:
static function doCurl($url, $username = null, $password = null) {
if (!function_exists('curl_init')) {
// throw error
}
$ch = curl_init();
$opts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_TIMEOUT => 120,
CURLOPT_FAILONERROR => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY
);
if ($password != null && $username != null) {
$opts[CURLOPT_USERPWD] = "$username:$password";
}
curl_setopt_array($ch, $opts);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
usage is:
doCurl("http://hostNameHere:8983/solr/select/?q=solr&start=0&rows=10&indent=on", "user", "pass");
Your issue is that you are never issuing a command to Solr to add the document that you have built to your index. You are only issuing the commit command, which is executing successfully.
Since you are using PHP, I would recommend using the PHP SolrClient. This will save you from having to manually write all of the functions (add, delete, commit, etc.) yourself. In this case, you would need to call the addDocument function.
i am inserting some data to an salesforce object named as Application__c from php using Soapclient. After connection successfull, i have written following code
$applications = array();
$updateFields = array();
if($_POST['savingsAccountBankName'] != ''){
$updateFields['savings_account_bank_name__c']= $_POST['savingsAccountBankName'];
}
if($_POST['AutoMake'] != ''){
$updateFields['Auto_make__c']= $_POST['AutoMake'];
}
if($_POST['AutoLicense'] != ''){
$updateFields['Auto_license__c']= $_POST['AutoLicense'];
}
$sObject = new sObject();
$sObject->type = 'Application__c';
$sObject->fields = $updateFields;
array_push($applications, $sObject);
try {
$results = $sforceClient->create($applications,'Application__c');
foreach ($results as $result)
{
$errMessage = $result->errors->message;
echo $errMessage;
}
} catch (Exception $e) {
echo 'Salesforce Upsert Error. Please try again later.';
echo '<pre>';
print_r($e);
echo '</pre>';
}
i am getting error "Trying to get property of non-object" at line "$errMessage = $result->errors->message;". What is the problem?
thanks
Be aware that $result is an array..
Try this :
if (!isset($result[0]->success) || ($result[0]->success!=1)) {
$strErrCode = isset($result[0]->errors[0]->statusCode)?
$result[0]->errors[0]->statusCode:'CANNOT_INSERT';
$strErrMsg = isset($result[0]->errors[0]->message)?
$result[0]->errors[0]->message:'Error Trying to insert';
$arrResult = array(
'errorCode' => $strErrCode,
'errorMsg' => $strErrMsg,
'id' => '',
);
error_log( 'Error Trying to insert - [' . $strErrMsg . '] - [' . $strErrCode . ']');
}
if (isset($result[0]->success) && ($result[0]->success==1)) {
$arrResult = array(
'errorCode' => 'SUCCESS_INSERT',
'errorMsg' => 'Insert Success',
'id' => isset($result[0]->id)?$result[0]->id:'1',
);
error_log( 'Success insert - [' . (isset($result[0]->id)?$result[0]->id:'1') . ']');
}
This means that whatever $results contains, it is not an object. Try doing a var_dump() on the variable $results and see what is actually in there. Then you can properly reference it.
Well I am trying to post on facebook's wall but I get this error:
Fatal error: Call to undefined method stdClass::stream_publish()
The code I am trying is this
<?php
define('FB_APIKEY', '<Your Api Key>');
define('FB_SECRET', '<Secret>');
define('FB_SESSION', '<Session>');
require_once('facebook.php');
echo "post on wall";
echo "<br/>";
try {
$facebook = new Facebook(FB_APIKEY, FB_SECRET);
$facebook->api_client->session_key = FB_SESSION;
$facebook->api_client->expires = 0;
$message = '';
$attachment = array(
'name' => $_POST["name"],
'href' => $_POST["href"],
'description' => $_POST["description"],
'media' => array(array('type' => 'image',
'src' => $_POST["src"],
'href' => $_POST["href"])));
$action_links = array( array('text' => 'Visit Us', 'href' => '<link to some place here>'));
$attachment = json_encode($attachment);
$action_links = json_encode($action_links);
$target_id = "<Target Id>";
$session_key = FB_SESSION;
if( $facebook->api_client->stream_publish($message, $attachment, $action_links, null, $target_id)) {
echo "Added on FB Wall";
}
} catch(Exception $e) {
echo $e . "<br />";
}
?>
Well, as it is written in the error message there is no method "stream_publish" in $facebook->api_client.
Consult the manual of the library you are using to connect to the facebook.
If $facebook->api_client is not an object, then the line:
$facebook->api_client->session_key = FB_SESSION;
Will make php silently cast $facebook->api_client to an object of type stdClass. Which, later on down the code, will cause the Fatal error: Call to undefined method stdClass::stream_publish() that you are getting.
Try changing:
...
$facebook = new Facebook(FB_APIKEY, FB_SECRET);
$facebook->api_client->session_key = FB_SESSION;
$facebook->api_client->expires = 0;
...
to catch for when api_client is false (or, perhaps, not an object):
...
$facebook = new Facebook(FB_APIKEY, FB_SECRET);
if (!( $facebook->api_client )) {
//throw error
echo 'Need to sort this bit out';
exit;
}
$facebook->api_client->session_key = FB_SESSION;
$facebook->api_client->expires = 0;
...
And then, if that does throw an error, you'd need to investigate why $facebook->api_client is null.