php DomDocument : Match each nodeValue, add attribute to its nodeName if condition satisfies [closed] - domdocument

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Check for each text node whether or not it exists in DataBase, if it does then add a class to its Element node.
I have tried do it the following way :
function extractText($node) {
if (XML_TEXT_NODE === $node->nodeType || XML_CDATA_SECTION_NODE === $node->nodeType) {
// am considering that Login is the word that exists in DB
if ($node->nodeValue == "Login"):
$node->setAttribute("class", "translated");
return $node->nodeName;
endif;
} else if (XML_ELEMENT_NODE === $node->nodeType || XML_DOCUMENT_NODE === $node->nodeType
|| XML_DOCUMENT_FRAG_NODE === $node->nodeType) {
if ('script' === $node->nodeName || 'style' === $node->nodeName)
return '';
$text = '';
foreach ($node->childNodes as $childNode) {
$text .= extractText($childNode);
}
return $text;
}
}
$doc = new DomDocument;
$doc->loadHTMLFile('test.html');
//var_dump(extractText($doc->getElementsByTagName('body')->item(0)));
echo extractText($doc->getElementsByTagName('body')->item(0));
But it gives Error message.
Fatal error: Call to undefined method DOMText::setAttribute()

Fatal error: Call to undefined method DOMText::setAttribute()
Well, let's look at the code.
if (XML_TEXT_NODE === $node->nodeType || XML_CDATA_SECTION_NODE === $node->nodeType) {
// am considering that Login is the word that exists in DB
if ($node->nodeValue == "Login"):
$node->setAttribute("class", "translated");
return $node->nodeName;
endif;
} /* else ... */
You're asking exclusively for text or CDATA nodes, then you're trying to set an attribute ... on the text. This won't work. Text nodes can't have attributes.
You need to get to the element containing the text and add the attribute there. Because DOMText inherits from DOMNode, you can inspect the parentNode property and probably get an element back.

Related

How to resolve 'groovy.lang.MissingMethodException' ...Possible solutions: notify(), render(java.lang.String)

I am very new to Groovy and this is an old application where the author is no longer with our organization. None of the previous questions that look similar offered any help. The application needs to send a simple message to the user to warn they are missing an entry before they con continue on.
I have made no fewer than 20 changes from flash.message to confirm. Flash causes the application to jump all the way to the user login function. This confirm is giving a crash message: Error 500: Executing action [submitrequest] of controller [SdrmController] caused exception: Runtime error executing action
def submitrequest = {
def testChecker
testChecker = [params.fullExpName].flatten().findAll { it != null }
log.info('testChecker.size = ' + testChecker.size)
if (testChecker.size > 0) {
if (!confirm('Submitting can not be undone, are you sure?')) return
} else {
if (!confirm('You have to pick an expedition. Please return to your Request and pick at least one expedition.')) return
} else {
return
}
}
// rest of long time working code here
}
Expected Result is a simple message to screen tell the user to pick an "Expedition" from a list and then the code returns to the same point so the user can make the change then hit the submit again.
Then full message:
No signature of method: SdrmController.confirm() is applicable for argument types: (java.lang.String) values: [You have to pick an expedition. Please return to your Request and pick at least one expedition.] Possible solutions: notify(), render(java.lang.String)
-- flash.message worked for our situation.
`legChecker = [params.programLeg].flatten().findAll{it!=null}
if(requestInstance.futurePast == "future" && expChecker.size<1) {
flash.message = " you must select a future expedition "
render(view: 'stepstart', model: [....])
return
}`

Modifying list and sending it to front end sends original list

I couldn't phrase my Title better, but what's happening is: I fetch a list when the page opens, but it should remove one member of it based on something the user does on the page.
I'm using a ui:repeat in the front-end, and the getter method of this list is:
public List<Employee> getAvailableLoaders() {
if (availableLoaderList != null) {
List<Employee> availableLoaderListWithoutDriver = new ArrayList(availableLoaderList);
if (selectedDriver != null) {
logInfo("SelectedDriver is: " + selectedDriver.getName());
logInfo("List's size before removal is: " + availableLoaderListWithoutDriver.size());
logInfo("Removal was successfull? " + availableLoaderListWithoutDriver.remove(selectedDriver));
logInfo("List's size after removal is: " + availableLoaderListWithoutDriver.size());
}
return availableLoaderListWithoutDriver;
}
return null;
}
And my logs say:
Info: SelectedDriver is: [Driver name]
Info: List's size before removal is: 5
Info: Removal was successful? true
Info: List's size after removal is: 4
But it still shows a list with the driver removed and 5 members anyway. I know the getter is being called with the correct info and when the place that shows it is called because I'm watching the logs.
Any explanation or suggestion on how should I do this or am I just doing a really stupid mistake?

How to integrate the element label into the validation error message in ZF2?

I have a form, where the error messages have to be displayed bundled at one place. The default messages are general, so the user sometimes doesn't know, which message is for which form field:
A record matching the input was found
Value is required and can't be empty
The input is not a valid email address...
I could write a custom message for every field, but is much effort and copy&paste.
So, I'd like to display the messages like this:
My element Foo label: A record matching the input was found
My element Bar label: Value is required and can't be empty
My element Buz label: The input is not a valid email address...
How to achieve this?
ZF2 seems not to provide a solution for this requirement. My solution/workaround is to override the Zend\Form\View\Helper\FormElementErrors replacing these lines of the FormElementErrors#render(...) by
$this->prepareMessagesToPrint($messages, $messagesToPrint, $element, $escapeHtml);
and add a method, that process the $messages as desired:
protected function prepareMessagesToPrint($messages, &$messagesToPrint, $element, $escapeHtml) {
foreach ($messages as $nameOrType => $elementOrError) {
if (is_string($elementOrError)) {
$elementLabel = $element->getLabel()
? '<b>' . $this->view->translate($element->getLabel()) . '</b>' . ': '
: null
;
$message = $escapeHtml($elementOrError);
$messagesToPrint[] = $elementLabel ? $elementLabel . $message : $message;
} elseif (is_array($elementOrError)) {
$newElement = $element->get($nameOrType);
$this->prepareMessagesToPrint(
$elementOrError, $messagesToPrint, $newElement, $escapeHtml
);
}
}
}

The youtube API sometimes throws error: Call to a member function children() on a non-object

When i launch the php script, sometime works fine, but many other times it retrieve me this errror
Fatal error: Call to a member function children() on a non-object in
/membri/americanhorizon/ytvideo/rilevametadatadaurlyoutube.php on line
21
This is the first part of the code
// set feed URL
$feedURL = 'http://gdata.youtube.com/feeds/api/videos/dZec2Lbr_r8';
// read feed into SimpleXML object
$entry = simplexml_load_file($feedURL);
$video = parseVideoEntry($entry);
function parseVideoEntry($entry) {
$obj= new stdClass;
// get nodes in media: namespace for media information
$media = $entry->children('http://search.yahoo.com/mrss/'); //<----this is the doomed line 21
UPDATE: solution adopted
for ($i=0 ; $i< count($fileArray); $i++)
{
// set feed URL
$feedURL = 'http://gdata.youtube.com/feeds/api/videos/'.$fileArray[$i];
// read feed into SimpleXML object
$entry = simplexml_load_file($feedURL);
if (is_object($entry))
{
$video = parseVideoEntry($entry);
echo ($video->description."|".$video->length);
echo "<br>";
}
else
{
$i--;
}
}
In this mode i force the script to re-check the file that caused the error
You are first of all calling a function:
$entry = simplexml_load_file($feedURL);
That function has a return value. You find it documented on the manual page of that function:
http://php.net/simplexml_load_file
Then you use that return value in form of a variable $entry without verifying that the function call was successful.
Because of that, you run into an error next. However your error/mistake is how you treat the return value of the function.
Not dealing with return values properly is like calling for trouble. Read about the function you use, check the return value(s) and proceed according to success or error conditions.
$entry = simplexml_load_file($feedURL);
if (FALSE === $entry)
{
// youtube not available.
}
else
{
// that's what I love!
}
Sometimes? Really?
Take a look at this:
<?php
$dummy; //IN FACT, this var is NULL now
// Will throw exactly the same error you get
$dummy->children();
Why? Because, we can call method from an object type.
So, if you wanna avoid errors like this one, next time you would call the method ensure that it's "possible".
<?php
if ( is_object($dummy) && method_exists($dummy, 'children') ){
//sure it works
$dummy->children();
}

Null pointer exception when parsing Node Value in Blackberry [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to parse empty node value in Blackberry
I am getting the response from web service as below.
<section id="2"></section>
<section id="2">xxx</section>
Now to parse the above response i wrote the code as below
speakersnode=speaker.getElementsByTagName("section");
for(int k=0;k<speakersnode.getLength();k++)
{
System.out.println("speaker "+speakersnode.item(k).getFirstChild().getNodeValue());
vspeakers.addElement(speakersnode.item(k).getFirstChild().getNodeValue());
}
When i parsing it i am getting null pointer exception here.
Now i chaged the code as follow
speakersnode=speaker.getElementsByTagName("section");
for(int k=0;k<speakersnode.getLength();k++)
{
if(speakersnode.item(k).getFirstChild().getNodeValue() !=null)
{
System.out.println("speaker "+speakersnode.item(k).getFirstChild().getNodeValue());
vspeakers.addElement(speakersnode.item(k).getFirstChild().getNodeValue());
}
}
But still i am getting the null pointer exception how
Try this:
speakersnode=speaker.getElementsByTagName("speaker");
for(int k=0;k<speakersnode.getLength();k++)
{
ids.addElement(((Element)speakersnode.item(k)).getAttribute("id"));
String info = speakersnode.item(k).getFirstChild().getNodeValue();
if (info == null){
info = "";
}
System.out.println("speaker "+ info );
vspeakers.addElement(info);
}
You also need to learn how to debug. And how to handle exceptions. You will lear how to fix this kind of stuff in seconds

Resources