XML is not parsed in php - php

In my controller, I read a data from DB. (where AlarmDeatils is a stored as XML content. Eg:AlarmDeatils column contains
<SiteAlarmDetails>
<AlertId>89637</AlertId>
<SiteCode>20157498</SiteCode>
<SiteName>newport</SiteName>
<TankNumber>4</TankNumber>
<DispenserNumbedr>3</DispenserNumbedr>
<HoseNumber>3</HoseNumber>
<GradeId>11</GradeId>
<GradeName>PULP98</GradeName>
<AlarmUTCDateTime>2015-10-08T12:00:00</AlarmUTCDateTime>
<AlarmClearedUTCDateTime>2015-10-08T22:00:00</AlarmClearedUTCDateTime>
<UTCTimeZoneName>GMT Standard Time</UTCTimeZoneName>
<AlarmVolume>0</AlarmVolume>
<AlarmLevel>0</AlarmLevel>
<TankCapacity>0</TankCapacity>
<TankCapacityPercent>0</TankCapacityPercent>
<TankOverfill>0</TankOverfill>
<TankUllage>0</TankUllage>
<ProductLoss>0</ProductLoss>
<HoursElapsed>10</HoursElapsed>
<WaterLevel>0</WaterLevel>
<AvgSalesPerDay>0</AvgSalesPerDay>
<DaysToStockOut>0</DaysToStockOut>
<InvalidDataCount>0</InvalidDataCount>
<ValidDataCount>0</ValidDataCount>
<ZeroVolumeCount>0</ZeroVolumeCount>
<ZeroProductLevelCount>0</ZeroProductLevelCount>
<ZeroTotaliserAmountCount>0</ZeroTotaliserAmountCount>
</SiteAlarmDetails>
I read that that row in my controller like;
$tableAlarm = \DB::table('Alarm')
->where('Alarm.AlarmId', '=', $id)->first();
and when I use
var_dump($tableAlarm);
I get
object(stdClass)#241 (10) { ["AlarmId"]=> string(6) "245039" ["MessageNotificationId"]=> string(6) "219078" ["CompanyId"]=> string(2) "19" ["CompanyCode"]=> string(7) "MCCOLLS" ["AlertTypeId"]=> string(2) "23" ["AlarmDetails"]=> string(1408) "979381320106510Eyemouth Service Station2017-07-23T21:26:499999-12-31T23:59:59.9999999GMT Standard Time00000005000000000001-01-01T00:00:000001-01-01T00:00:000001-01-01T00:00:000000001-01-01T00:00:00" ["AlertProcessStateId"]=> string(1) "2" ["UTCDateTimeInserted"]=> string(27) "2017-07-24 02:15:36.9300000" ["UTCDateTimeUpdated"]=> string(27) "2017-07-24 02:15:36.9300000" ["RowDataVersion"]=> string(16) "00000000117D854B" }
Im trying to parse the AlarmDeatils column like;
$alertXml = simplexml_load_string( $tableAlarm->AlarmDetails);
echo $alertXml;//Nothing printed
But i'm not getting anything :( I'm trying to process that xml like;
foreach($alertXml->children() as $alerts)
{
print_r( $alerts->AlertId);// **getting SimpleXMLElement Object ()**
echo $alerts->AlertId;//**Nothing printed**
}

Hope this will be helpful. Try this simplest one.
Try this code snippet here
<?php
$xmlString=<<<XML
<SiteAlarmDetails>
<AlertId>89637</AlertId>
<SiteCode>20157498</SiteCode>
<SiteName>newport</SiteName>
<TankNumber>4</TankNumber>
<DispenserNumbedr>3</DispenserNumbedr>
<HoseNumber>3</HoseNumber>
<GradeId>11</GradeId>
<GradeName>PULP98</GradeName>
<AlarmUTCDateTime>2015-10-08T12:00:00</AlarmUTCDateTime>
<AlarmClearedUTCDateTime>2015-10-08T22:00:00</AlarmClearedUTCDateTime>
<UTCTimeZoneName>GMT Standard Time</UTCTimeZoneName>
<AlarmVolume>0</AlarmVolume>
<AlarmLevel>0</AlarmLevel>
<TankCapacity>0</TankCapacity>
<TankCapacityPercent>0</TankCapacityPercent>
<TankOverfill>0</TankOverfill>
<TankUllage>0</TankUllage>
<ProductLoss>0</ProductLoss>
<HoursElapsed>10</HoursElapsed>
<WaterLevel>0</WaterLevel>
<AvgSalesPerDay>0</AvgSalesPerDay>
<DaysToStockOut>0</DaysToStockOut>
<InvalidDataCount>0</InvalidDataCount>
<ValidDataCount>0</ValidDataCount>
<ZeroVolumeCount>0</ZeroVolumeCount>
<ZeroProductLevelCount>0</ZeroProductLevelCount>
<ZeroTotaliserAmountCount>0</ZeroTotaliserAmountCount>
</SiteAlarmDetails>
XML;
$xml=simplexml_load_string($xmlString);
echo (string)$xml->AlertId;//type-casted to string
echo PHP_EOL;
echo (string)$xml->SiteCode;
echo PHP_EOL;
echo (string)$xml->SiteName;

Related

Loop through array from NIST API.. Cant get it working

Im working with some data from the NIST CVE Database.
Im putting it through the simpleXMLElement array but cant figure out how to loop through it properly.
Tried following other threads here but cant it working.. These miltidimensional? arrays break me.
Any help would be super great!
Here is the array dump:
object(SimpleXMLElement)#1 (2) {
["channel"]=>
object(SimpleXMLElement)#2 (4) {
["title"]=>
string(31) "National Vulnerability Database"
["link"]=>
string(41) "https://web.nvd.nist.gov/view/vuln/search"
["description"]=>
string(114) "This feed contains the most recent CVE cyber vulnerabilities published within the National Vulnerability Database."
["items"]=>
object(SimpleXMLElement)#151 (0) {
}
}
["item"]=>
array(148) {
[0]=>
object(SimpleXMLElement)#3 (3) {
["title"]=>
string(35) "CVE-2008-6594 (rdf_newsfeed_export)"
["link"]=>
string(62) "https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2008-6594"
["description"]=>
string(150) "SQL injection vulnerability in the cm_rdfexport extension for TYPO3 allows remote attackers to execute arbitrary SQL commands via unspecified vectors."
}
[1]=>
object(SimpleXMLElement)#4 (3) {
["title"]=>
string(26) "CVE-2014-5129 (projectdox)"
["link"]=>
string(62) "https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2014-5129"
["description"]=>
string(162) "Cross-site scripting (XSS) vulnerability in Avolve Software ProjectDox 8.1 allows remote attackers to inject arbitrary web script or HTML via unspecified vectors."
}
[2]=>
object(SimpleXMLElement)#5 (3) {
["title"]=>
string(24) "CVE-2019-9565 (antidote)"
["link"]=>
string(62) "https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2019-9565"
["description"]=>
string(467) "Druide Antidote RX, HD, 8 before 8.05.2287, 9 before 9.5.3937 and 10 before 10.1.2147 allows remote attackers to steal NTLM hashes or perform SMB relay attacks upon a direct launch of the product, or upon an indirect launch via an integration such as Chrome, Firefox, Word, Outlook, etc. This occurs because the product attempts to access a share with the PLUG-INS subdomain name; an attacker may be able to use Active Directory Domain Services to register that name."
}
Im using this code but it just echos "item" each time..
$xml = new SimpleXMLElement($apiData);
var_dump($xml);
$i="0";
foreach ($xml->item as $key => $value) {
echo $xml['item']['$i']['link']; // get the CVE link..
echo "KEY:$key Value:$value \r\n";
$i ++;
}
You should use the -> notation for getting the link. The array index is what you called the key. So I would name that $i:
foreach ($xml->item as $i => $item) {
$link = $item->link;
echo "Index:$i Link:$link \r\n";
}

PHP XML converter response

im quite new on XML, i am currently work in PHP and i have a request to other server which normaly and always return the callback with XML
In any case i would not talk about how i get the response, but how to convert the XML reponse.
They are two type of the XML response, we could call it as $response
first :
<BASEELEMENT SCHEMA="RESULT" METHOD="ADD-MBX">
<RETURN_VALUE>4</RETURN_VALUE>
<ERROR_DESCRIPTION>
<![CDATA[Error (7004): Login name already exists. Please use another login name.]]>
</ERROR_DESCRIPTION>
</BASEELEMENT>
and the second one is :
<baseelement schema="TIMEOUT" method="ADD-MBX"></baseelement>
i have searched and i got how to convert the xml reponse to obejct or array, which is
$response = new \SimpleXMLElement($response);
after convert :
object(SimpleXMLElement)#256 (3) {
["#attributes"]=>
array(2) {
["SCHEMA"]=>
string(6) "RESULT"
["METHOD"]=>
string(7) "ADD-MBX"
}
["RETURN_VALUE"]=>
string(1) "4"
["ERROR_DESCRIPTION"]=>
object(SimpleXMLElement)#257 (0) {
}
}
as we can see the ERROR_DESCRIPTION become 0.
So i would like to ask, is there any xml converter else simplexml_load_string() or new \SimpleXMLElement()
i cant use that function because i could not get the ERROR_DESCRIPTION
thank you :)
Loading it as you are with -
$response = new \SimpleXMLElement($response);
You can fetch the value quite simply as...
echo (string)($response->ERROR_DESCRIPTION).PHP_EOL;
If you want the full content (as in an XML version)...
echo $response->ERROR_DESCRIPTION->asXML().PHP_EOL;
Using XPath, you can fetch the values by...
echo (string)$response->xpath("//ERROR_DESCRIPTION")[0].PHP_EOL;
The output you are seeing shows that ERROR_DESCRIPTION is an object of SimpleXMLElement type, not that it isn't loaded.

your data could not be encoded because it contains invalid UTF8 characters jms/serializer-bundle symfony

I am trying to serialize the data of -doctrine repository function- result into JSON format, the operation faild... I am using jms/serializer-bundle... I need your help please
$em = $this->getDoctrine()
->getManager();
$repository = $em->getRepository('navormvagBundle:Stationpompage');
$data = $repository->find($id);
$serializer = $this->container->get('serializer');
$data = $serializer->serialize($data, 'json');
CRITICAL - Uncaught PHP Exception RuntimeException: "Your data could not be encoded because it contains invalid UTF8 characters." at C:\ms4w\Apache\htdocs\ormvagProject\vendor\jms\serializer\src\JMS\Serializer\JsonSerializationVisitor.php line 36
var_dump($data);
object(nav\ormvagBundle\Entity\Communes)#358 (21) { ["objectid12":"nav\ormvagBundle\Entity\Communes":private]=> int(14) ["objectid1":"nav\ormvagBundle\Entity\Communes":private]=> int(14) ["objectid":"nav\ormvagBundle\Entity\Communes":private]=> int(461) ["codeCommu":"nav\ormvagBundle\Entity\Communes":private]=> string(13) "04.291.05.11." ["nomCommun":"nav\ormvagBundle\Entity\Communes":private]=> string(6) "OULMES" ["typeCommu":"nav\ormvagBundle\Entity\Communes":private]=> string(1) "R" ["codeProvi":"nav\ormvagBundle\Entity\Communes":private]=> string(6) "04.291" ["codeRegio":"nav\ormvagBundle\Entity\Communes":private]=> string(2) "04" ["pop2014":"nav\ormvagBundle\Entity\Communes":private]=> int(18786) ["m�nages":"nav\ormvagBundle\Entity\Communes":private]=> int(4688) ["etrangers":"nav\ormvagBundle\Entity\Communes":private]=> float(1) ["marocains":"nav\ormvagBundle\Entity\Communes":private]=> int(18785) ["nomCercle":"nav\ormvagBundle\Entity\Communes":private]=> string(6) "Oulmes" ["x":"nav\ormvagBundle\Entity\Communes":private]=> float(441447.171109) ["y":"nav\ormvagBundle\Entity\Communes":private]=> float(310925.203251) ["nomProvin":"nav\ormvagBundle\Entity\Communes":private]=> string(9) "Khemisset" ["shapeLeng":"nav\ormvagBundle\Entity\Communes":private]=> float(146137.539535) ["codeCercl":"nav\ormvagBundle\Entity\Communes":private]=> string(9) "04.291.05" ["shapeLength":"nav\ormvagBundle\Entity\Communes":private]=> float(146137.54067987) ["shapeArea":"nav\ormvagBundle\Entity\Communes":private]=> float(542883719.60999) ["wkbGeometry":"nav\ormvagBundle\Entity\Communes":private]=> string(26344) "SRID=900914;MULTIPOLYGON(((446016.130999997 319730.371199999,446125.634599999 319486.142200001,446254.220299996 319308.2588,446308.889600001 319175.070700001,446355.217600003 319163.748,446550.325000003 319184.854800001,446615.303800002 319184.508400001,446652.349200003 319173.236499999,446762.549800001 319017.605599999,446827.104000002 318961.889600001,446929.385200001 318983.4965,447125.511100002 319137.504700001 )))" }
I got it. m�nages not valid property name of the entity.
That's why serializer fired error.
Check your property names, file format (must be UTF-8) and also database configuration.
Hope, this will be helpful.
Good luck.

PHPmyGraph: send an array with GET

I could not find any answer to my question.
I'm using PhPmyGraph ( http://phpmygraph.abisvmm.nl/ ) to display a graph of some data from my databases.
The problem is that I have to create my arrays in the file itself, and if I want 2 graphs on the page I need to create 2 different files.
Apparently the file is easier to use with a CMS but I'm not using one.
This is the file graph.php:
<?php
//Set content-type header for the graphs
header("Content-type: image/png");
//Include phpMyGraph5.0.php
include_once('../phpMyGraph5.0.php');
//Set config directives
$cfg['title'] = 'Example graph';
$cfg['width'] = 500;
$cfg['height'] = 250;
//Set data
$data = array(
'Jan' => 12,
'Nov' => 78,
'Dec' => 23
);
//Create phpMyGraph instance
$graph = new phpMyGraph();
//Parse
$graph->parseVerticalPolygonGraph($data, $cfg);
?>
I call it in my page index.php:
echo " < img src=\"graph.php\"> ";
Is there another way to do it? And send the data from index.php to graph.php?
Or maybe move the code graph.php into index.php ? The problem is for the image object, I don't really know how to do it!
UPDATE:
I have almost found a solution, my code is now:
in graph.php:
//Parse
$graph->parseVerticalPolygonGraph(unserialize($_GET['data']), $cfg);
index.php :
$select_daily = mysql_query("SELECT * FROM table");
while ($row_daily = mysql_fetch_assoc($select_daily) ){
$y = substr($row_daily['ymd'], 0, -4); // Year
$m = substr($row_daily['ymd'], 4, -2); // Month
$d = substr($row_daily['ymd'], -2); // Day
$key = $d."/".$m."/".$y;
$data_daily [$key] = $row_daily['members'];
}
foreach($data_daily as $key => $value) {
echo $key ,' : ', $value ,'<br/>';
}
echo "< img src=\"graph.php?data=".serialize($data_daily)."\">";
But I get the error "provided data is not an array"
I can't see what's wrong with it?
if I do var_dump($data_daily) I get:
array(8) { ["14/12/2011"]=> string(1) "0" ["13/12/2011"]=> string(2)
"11" ["12/12/2011"]=> string(1) "0" ["11/12/2011"]=> string(1) "2"
["10/12/2011"]=> string(1) "9" ["09/12/2011"]=> string(1) "3"
["08/12/2011"]=> string(1) "6" ["07/12/2011"]=> string(1) "6" }
UPDATE2:
var_dump($data1); gives:
array(12) { ["Jan"]=> int(12) ["Feb"]=>
int(25) ["Mar"]=> int(0) ["Apr"]=> int(7) ["May"]=> int(80) ["Jun"]=>
int(67) ["Jul"]=> int(45) ["Aug"]=> int(66) ["Sep"]=> int(23)
["Oct"]=> int(23) ["Nov"]=> int(78) ["Dec"]=> int(23) }
and var_dump($s_data1 = serialize($data1)) gives:
a:12:s:3:"Jan";i:12;s:3:"Feb";i:25;s:3:"Mar";i:0;s:3:"Apr";i:7;s:3:"May";i:80;s:3:"Jun";i:67;s:3:"Jul";i:45;s:3:"Aug";i:66;s:3:"Sep";i:23;s:3:"Oct";i:23;s:3:"Nov";i:78;s:3:"Dec";i:23;}
Then unserialize($s_data1); gives the same thing than $data1
So the argument 1 of the parse should be correct... I can’t see what is wrong
I finally gave up and loaded my arrays in graph.php:
if ($_GET['data'] == 'daily'){
$cfg['title'] = 'daily';
$graph->parseVerticalPolygonGraph($data_daily, $cfg);
}
And I call the file like that:
echo "<img src=\"graph.php?data=daily\">";
Thanks for your help anyway
I previously needed a page to display multiple graphs using phpMyGraph and the approach I took was to use data URI's and php's ob_start() and ob_get_clean()
Simply use this for each graph:
ob_start();
$graph->parseVerticalPolygonGraph($data, $cfg);
$img = ob_get_clean();
echo "<img src='data:image/gif;base64," . base64_encode($img) . "/>";
I recommend using gif's for the format since that way your page size will not be huge, you can do this by setting $cfg["type"] to "gif" (See here http://phpmygraph.abisvmm.nl/#ConfigDirectives)
This will also reduce the overhead of multiple requests and prevent hotlinking to the images.
You can read more about data URI's here
http://en.wikipedia.org/wiki/Data_URI_scheme
you might want to try
echo "< img src=\"graph.php?data=".urlencode(serialize($data_daily))."\">"
I might be misunderstanding which script is throwing the error, however (I'm presuming that it's graph.php that's giving you the provided data is not an array).
Try using json instead of serialize
echo "< img src=\"graph.php?data=".urlencode(json_encode($data_daily))."\">"
$graph->parseVerticalPolygonGraph(json_decode($_GET['data'],true), $cfg);
I see no reason for this to throw an error.

php xml function requirements

hi i am using the xml function simplexml_load_string for reading the xml string but there is no any output of this function i also use dom function but the same response of this.
is there any another method of reading the xml?
or is there any modification require on server to enable these function
There are are many reasons why you might end up with no output at all. Some I can think of are:
There's a parse error in your script and your php version is not configured to show startup errors. see display_startup_errors and/or add some unconditional output to the script (so that if this output is missing you know the script didn't even reach that statement).
The script doesn't reach the statement because of some conditions ( `if (false) { ... } ). Again add some output and/or use a debugger to see if the statement is reached.
The string contains something that is not valid xml and therefore the libxml parser gives up and simplexml_load_string() returns false. Test the return value and maybe check the errors libxml may have encountered, see http://docs.php.net/function.libxml-use-internal-errors
The SimpleXML module isn't present (though in recent versions of php it's enabled by default). Use extension_loaded() and/or function_exists() to test this.
Try it again with a bit more error handling, e.g.
<?php
// this is only for testing purposes
// set those values in the php.ini of your development server if you like
// but use a slightly more sophisticated error handling/reporting mechanism in production code.
error_reporting(E_ALL); ini_set('display_errors', 1);
echo 'php version: ', phpversion(), "\n";
echo 'simplexml_load_string() : ', function_exists('simplexml_load_string') ? 'exists':"doesn't exist", "\n";
$xml = '<a>
>lalala
</b>
</a>';
libxml_use_internal_errors(true);
$doc = simplexml_load_string($xml);
echo 'errors: ';
foreach( libxml_get_errors() as $err ) {
var_dump($err);
}
if ( !is_object($doc) ) {
var_dump($doc);
}
echo 'done.';
should print something like
php version: 5.3.2
simplexml_load_string() : exists
errors: object(LibXMLError)#1 (6) {
["level"]=>
int(3)
["code"]=>
int(76)
["column"]=>
int(7)
["message"]=>
string(48) "Opening and ending tag mismatch: a line 1 and b
"
["file"]=>
string(0) ""
["line"]=>
int(3)
}
object(LibXMLError)#2 (6) {
["level"]=>
int(3)
["code"]=>
int(5)
["column"]=>
int(1)
["message"]=>
string(41) "Extra content at the end of the document
"
["file"]=>
string(0) ""
["line"]=>
int(4)
}
bool(false)
done.

Categories