DOMDocument::loadXML() error - domdocument

When I use DOMDocument in PHP file, I get the following errors:
Warning: DOMDocument::loadXML() [domdocument.loadxml]: Premature end of data in tag nodes line 7 in Entity, line: 7 in D:\wamp\www\dom1.php on line 77
Warning: DOMDocument::loadXML() [domdocument.loadxml]: Premature end of data in tag node line 6 in Entity, line: 7 in D:\wamp\www\dom1.php on line 77
Warning: DOMDocument::loadXML() [domdocument.loadxml]: Premature end of data in tag field line 5 in Entity, line: 7 in D:\wamp\www\dom1.php on line 77
Warning: DOMDocument::loadXML() [domdocument.loadxml]: Premature end of data in tag field line 5 in Entity, line: 7 in D:\wamp\www\dom1.php on line 77
Warning: DOMDocument::loadXML() [domdocument.loadxml]: Premature end of data in tag field line 4 in Entity, line: 7 in D:\wamp\www\dom1.php on line 77
Warning: DOMDocument::loadXML() [domdocument.loadxml]: Premature end of data in tag field line 4 in Entity, line: 7 in D:\wamp\www\dom1.php on line 77
Warning: DOMDocument::loadXML() [domdocument.loadxml]: Premature end of data in tag node line 3 in Entity, line: 7 in D:\wamp\www\dom1.php on line 77
Warning: DOMDocument::loadXML() [domdocument.loadxml]: Premature end of data in tag node line 2 in Entity, line: 7 in D:\wamp\www\dom1.php on line 77
Warning: DOMDocument::loadXML() [domdocument.loadxml]: Premature end of data in tag node line 2 in Entity, line: 7 in D:\wamp\www\dom1.php on line 77
Warning: DOMDocument::loadXML() [domdocument.loadxml]: Premature end of data in tag nodes line 1 in Entity, line: 7 in D:\wamp\www\dom1.php on line 77
array(0) { }
The php code is as follows:
<?php
class MyDOMDocument extends DOMDocument
{
public function toArray(DOMNode $oDomNode = null)
{
// return empty array if dom is blank
if (is_null($oDomNode) && !$this->hasChildNodes()) {
return array();
}
$oDomNode = (is_null($oDomNode)) ? $this->documentElement : $oDomNode;
if (!$oDomNode->hasChildNodes()) {
$mResult = $oDomNode->nodeValue;
} else {
$mResult = array();
foreach ($oDomNode->childNodes as $oChildNode) {
// how many of these child nodes do we have?
// this will give us a clue as to what the result structure should be
$oChildNodeList = $oDomNode->getElementsByTagName($oChildNode->nodeName);
$iChildCount = 0;
// there are x number of childs in this node that have the same tag name
// however, we are only interested in the # of siblings with the same tag name
foreach ($oChildNodeList as $oNode) {
if ($oNode->parentNode->isSameNode($oChildNode->parentNode)) {
$iChildCount++;
}
}
$mValue = $this->toArray($oChildNode);
$sKey = ($oChildNode->nodeName{0} == '#') ? 0 : $oChildNode->nodeName;
$mValue = is_array($mValue) ? $mValue[$oChildNode->nodeName] : $mValue;
// how many of thse child nodes do we have?
if ($iChildCount > 1) { // more than 1 child - make numeric array
$mResult[$sKey][] = $mValue;
} else {
$mResult[$sKey] = $mValue;
}
}
// if the child is <foo>bar</foo>, the result will be array(bar)
// make the result just 'bar'
if (count($mResult) == 1 && isset($mResult[0]) && !is_array($mResult[0])) {
$mResult = $mResult[0];
}
}
// get our attributes if we have any
$arAttributes = array();
if ($oDomNode->hasAttributes()) {
foreach ($oDomNode->attributes as $sAttrName=>$oAttrNode) {
// retain namespace prefixes
$arAttributes["#{$oAttrNode->nodeName}"] = $oAttrNode->nodeValue;
}
}
// check for namespace attribute - Namespaces will not show up in the attributes list
if ($oDomNode instanceof DOMElement && $oDomNode->getAttribute('xmlns')) {
$arAttributes["#xmlns"] = $oDomNode->getAttribute('xmlns');
}
if (count($arAttributes)) {
if (!is_array($mResult)) {
$mResult = (trim($mResult)) ? array($mResult) : array();
}
$mResult = array_merge($mResult, $arAttributes);
}
$arResult = array($oDomNode->nodeName=>$mResult);
return $arResult;
}
}
$sXml = <<<XML
<nodes>
<node>text<node>
<node>
<field>hello<field>
<field>world<field>
<node>
<nodes>
XML;
$dom = new MyDOMDocument;
$dom -> loadXml($sXml);
var_dump($dom->toArray());
?>
source location:
http://bd.php.net/manual/en/class.domdocument.php

You need to close the elements e.g. </node> and </field>
<nodes>
<node>text<node>
<node>
<field>hello<field>
<field>world<field>
<node>
<nodes>
Change to:
<nodes>
<node>text</node>
<node>
<field>hello</field>
<field>world</field>
</node>
</nodes>

Change your XML into:
$sXml = <<<XML
<nodes>
<node>text</node>
<node>
<field>hello</field>
<field>world</field>
</node>
</nodes>
XML;
Notice the pair <nodes></nodes>, <node></node>, <field></field>. You have to match every opened tag with it's closed tag. See w3Schools for more about XML.

Related

Trying to query data where string has a single quote

Trying to go through a list of values where there might be one with a single quote in it. When I try to pass it through a function, it fails.
It gives the error,
Execution error in store procedure REPORT_PRESENTATION_DATA: SQL compilation error: parse error line 1 at position 164 near '<EOF>'. syntax error line 1 at position 158 unexpected 't'. At Statement.execute, line 90 position 41
I then add
myCommonValue = myCommonValue.replace("'","''");
but now get the error,
JavaScript execution error: Uncaught TypeError: Cannot read property 'replace' of null in REPORT_PRESENTATION_DATA at ' myCommonValue = myCommonValue.replace("'","''");' position 36 stackstrace: REPORT_PRESENTATION_DATA line: 85
Here's a code sample:
CREATE OR REPLACE PROCEDURE MY_SNOWFLAKE_PROCEDURE()
RETURNS VARIANT
LANGUAGE JAVASCRIPT
AS
$$
...
sqlText = ` SELECT fields FROM MYTABLE `;
statement = snowflake.createStatement({ sqlText });
const rs = statement.execute();
let results = [];
while (rs.next()) {
let myColumnValue = rs.getColumnValue(1);
myColumnValue = myColumnValue.replace("'","''");
// Using the column value which could contain a single quote in the string,
// get a second result set. IE: "gov't" may be the string value passed into Query_GroupValues
sqlText = ` SELECT * FROM table(Query_GroupValues('${startdate}', '${enddate}', ARRAY_CONSTRUCT('${myColumnValue}'))) `;
statement = snowflake.createStatement({ sqlText });
const rsTableValue = statement.execute();
if (statement.getRowCount() > 0) {
let myValue = rsTableValue.getColumnValue(1);
struct = {
attributes: {
value: myValue
}
}
results.push(struct);
}
}
...
$$;
Looks like myColumnValue was null when it's replace() method was invoked. Adding a guard should fix it. For Example: if (myColumnValue!=null) myColumnValue = myColumnValue.replace("'","''");

How to copy one line from one attribute to another attribute in DOORs

I'm trying to copy a line from DOORS one attribute and write that line into another attribute in DOORS.
more or less straight from the DXL manual
Object o = current // might be set in a loop
Regexp line = regexp2 ".*"
string sTextValue = o."Object Text"""
string sLastLine = ""
while (!null sTextValue && line sTextValue) {
sLastLine = sTextValue[match 0]
sTextValue = sTextValue [end 0 + 2:]
}
print "->" sLastLine "<-\n"
o."Other Attribute" = sLastLine

Invalid charset on $_POST

I'm with a problem about the charset of the $_POST. When I submited a form, case the string inserted on the InputText haved a special character or a accent, the value of this input on the $_POST array is corrupted with invalid characters.
Exemple:
I inserted on the input: "pão"
The $_POST show me: Array ( [input] => pão)
I'm using the CodeIgniter Framework with ISO-8859-1 charset. To improve my test, I used a mb_detect_encoding() and this function returned utf-8. :\
Below the code of important parts:
/*
|--------------------------------------------------------------------------
| Default Character Set
|--------------------------------------------------------------------------
|
| This determines which character set is used by default in various methods
| that require a character set to be provided.
|
*/
$config['charset'] = "iso-8859-1";
/*
|--------------------------------------------------------------------------
| Default Language
|--------------------------------------------------------------------------
|
| This determines which set of language files should be used. Make sure
| there is an available translation if you intend to use something other
| than english.
|
*/
$config['language'] = "portugues";
$db['default']['char_set'] = "latin1";
$db['default']['dbcollat'] = "latin1_swedish_ci";
Form that was submited:
<form action="HTTP://localhost/portalsibe/index.php/grupos/cadastro" id="form" accept-charset="utf8" method="POST" name="frmPadrao" target="" enctype="multipart/form-data">
Try this solution, insert this jquery function in your script:
Font
Credits:
Javier Poo, WeLinux S.A.
Oficina: 02-372.97.70, Celular:84039925
Bombero Ossa # 1010, Santiago
www.welinux.cl
jQuery.fn.extend({
param: function( a ) {
var s = [];
// If an array was passed in, assume that it is an array
// of form elements
if ( a.constructor == Array || a.jquery ){
// Serialize the form elements
jQuery.each( a, function(){
s.push(unescape(encodeURIComponent(escape(this.name))) + "=" + unescape(encodeURIComponent(escape(this.value))));
});
}
// Otherwise, assume that it's an object of key/value pairs
else{
// Serialize the key/values
for ( var j in a )
// If the value is an array then the key names need to be repeated
if ( a[j] && a[j].constructor == Array )
jQuery.each( a[j], function(){
s.push(unescape(encodeURIComponent(escape(j)) + "=" + encodeURIComponent(escape(this))));
});
else
s.push(unescape(encodeURIComponent(escape(j)) + "=" + encodeURIComponent(escape(a[j]))));
}
// Return the resulting serialization
return s.join("&").replace(/ /g, "+");
},
serialize: function() {
return this.param(this.serializeArray());
}
});
Can you change everything to utf8? Including database?
If yes, change all files, and set MySQL database (and tables) to utf8_general_ci. If you are using notepad++ to develop, go to Encoding > Encode in UTF-8 (em português Formatar > Codificação em UTF-8).
Try not to use ISO-8859-1 as character encoding.
Then you need to "transform" all your files and database do ISO-8859-1. Don't forget to add in your PHP/HTML files, the encoding.
For example, in HTML4: <meta http-equiv="Content-type" content="text/html;charset=ISO-8859-1"> and HTML5: <meta charset="ISO-8859-1">
Also, try to change teh enctype in your <form> tag to application/x-www-form-urlencoded and see if it works.

xml parsing node value

I have an xml file to upload in sql
the xml is like
<catalog>
<products>
<product>
<ID>0079</ID>
<NAME>Casa</NAME>
<feature name="material">cemento</feature>
</product>
</products>
</catalog>
I do:
$xml = simplexml_load_file('prova.xml');
$listProducts = $xml->products;
foreach ($listProducts->product as $product)
{
$name = $product->NAME;
$id= $product->ID;
....................
But the prodblem is when I must define the variable "FEATURE"
I want insert in my sql the value "CEMENTO"
How can I do?
See if it works
$feature = $product->feature;
$featureName = $product->feature->attributes()->name;
UPDATE
foreach ($listProducts->product as $product)
{
$name = $product->NAME;
$id= $product->ID;
foreach ($product->feature as $feature)
{
$featureName = $feature->attributes()->name;
}
...

How to parse text in Groovy

I need to parse a text (output from a svn command) in order to retrieve a number (svn revision).
This is my code. Note that I need to retrieve all the output stream as a text to do other operations.
def proc = cmdLine.execute() // Call *execute* on the strin
proc.waitFor() // Wait for the command to finish
def output = proc.in.text
//other stuff happening here
output.eachLine {
line ->
def revisionPrefix = "Last Changed Rev: "
if (line.startsWith(revisionPrefix)) res = new Integer(line.substring(revisionPrefix.length()).trim())
}
This code is working fine, but since I'm still a novice in Groovy, I'm wondering if there were a better idiomatic way to avoid the ugly if...
Example of svn output (but of course the problem is more general)
Path: .
Working Copy Root Path: /svn
URL: svn+ssh://svn.company.com/opt/svnserve/repos/project/trunk
Repository Root: svn+ssh://svn.company.com/opt/svnserve/repos
Repository UUID: 516c549e-805d-4d3d-bafa-98aea39579ae
Revision: 25447
Node Kind: directory
Schedule: normal
Last Changed Author: ubi
Last Changed Rev: 25362
Last Changed Date: 2012-11-22 10:27:00 +0000 (Thu, 22 Nov 2012)
I've got inspiration from the answer below and I solved using find(). My solution is:
def revisionPrefix = "Last Changed Rev: "
def line = output.readLines().find { line -> line.startsWith(revisionPrefix) }
def res = new Integer(line?.substring(revisionPrefix.length())?.trim()?:"0")
3 lines, no if, very clean
One possible alternative is:
def output = cmdLine.execute().text
Integer res = output.readLines().findResult { line ->
(line =~ /^Last Changed Rev: (\d+)$/).with { m ->
if( m.matches() ) {
m[ 0 ][ 1 ] as Integer
}
}
}
Not sure it's better or not. I'm sure others will have different alternatives
Edit:
Also, beware of using proc.text. if your proc outputs a lot of stuff, then you could end up blocking when the inputstream gets full...
Here is a heavily commented alternative, using consumeProcessOutput:
// Run the command
String output = cmdLine.execute().with { proc ->
// Then, with a StringWriter
new StringWriter().with { sw ->
// Consume the output of the process
proc.consumeProcessOutput( sw, System.err )
// Make sure we worked
assert proc.waitFor() == 0
// Return the output (goes into `output` var)
sw.toString()
}
}
// Extract the version from by looking through all the lines
Integer version = output.readLines().findResult { line ->
// Pass the line through a regular expression
(line =~ /Last Changed Rev: (\d+)/).with { m ->
// And if it matches
if( m.matches() ) {
// Return the \d+ part as an Integer
m[ 0 ][ 1 ] as Integer
}
}
}

Resources