Simplexml (invalid argument supplied foreach) - foreach

ERROR= Warning: Invalid argument supplied for foreach() in [path]/deals2.php on line 168
The XML: http://www.freeimagehosting.net/2sjdd
No idea what i'm doing wrong. Never ran into this issue before.
$xml = simplexml_load_file('http://api.yipit.com/v1/deals/?key=mykey&division=houston&format=xml');
foreach($xml->deals->list-item as $shortcut)
{
$title = $shortcut->{'title'};
echo $title;
}

There are no "deals" element name in your xml
Every element name that has a dash symbol '-' must be escaped with {'some-element'} so even if list-item element would exist (it does not) you would need to escape it. http://www.kombitz.com/2010/02/10/php-xml-problem-hyphen-in-the-element-name/
I modified your code to
foreach($xml->meta->code as $a) { echo $a; }
And it worked fine. Try my advice above and try using elements that actually exist.
And by the way, your XML is not even properly structured. What is that
<response/>
doing there?? A lot of errors. :)

Related

Remove all indents and spaces from JSON string except inside its value in Ruby

My problematic string is like this:
'{\n"test":"AAAA",\n"test2":"BBB\n\n\nBBB"\n}'
I want to parse it as JSON object(Hash) by JSON.parse(jsonstring)
The expecting result is:
{ "test": "AAAA", "test2": "BBB\nB"}
However, I get the error:
JSON::ParserError: 809
I happend to know that indentaion code in jsonstring be escaped,
so I tried this:
escaped_jsonstring = '{\n"test":"AAAA",\n"test2":"BBB\n\n\nBBB"\n}'.gsub(/\R/, '\\n')
JSON.parse(escaped_jsonstring)
I still have JSON::ParserError.
Indentations outside the key or value may cause this error.
How can I remove \n(or \r any indentation code) only outside the key or value in Ruby?
which means,
'{\n"test":"AAAA",\n"test2":"BBB\n\n\nBBB"\n}'
↓
'{"test":"AAAA","test2":"BBB\n\n\nBBB"}'
try this
'{\n"test":"AAAA",\n"test2":"BBB\n\n\nBBB"\n}'.gsub(/\B(\\n)+/, "")
\n" is considered inside boundary (so i use \B), meanwhile "\n is considered outside boundary (\b), (\\n)+ to fix case '...,\n\n\n"test2":...
update
turn out \s\n also be considered an inside boundary ... iam not sure there's other cases ...
for now, the updated version
'{\n"test":"AAAA",\n"test2":"BBB \n\n\n BBB"\n}'
.gsub(/([{,\"]\s*)\B(\\n)+/) { $1 }
better way
i found another way to solve your problem, also using regexp, now i will scan through the input text (valid or invalid json) then filter follow the pair pattern "<key>":"<value>" and don't care anything else outside those pairs, finally output the hash
def format(json)
matches = json.scan(/\"(?<key>[^\"]+)\":\"(?<val>[^\"]+)\",*/)
matches&.to_h
end
format('{\n "test\n parser":"AA\nAA", \n\n"test2":"BBB ? ;\n\n\n BBB" \n}')
# {"test\n parser"=>"AA\nAA", "test2"=>"BBB ? ;\n\n\n BBB"}

#HttpContext.Current.User.Identity.Name not showing backslash

Super Simple. Only issues I find are people getting null. Which I obvi fixed. But where is the backslash???!!
params.me = '#HttpContext.Current.User.Identity.Name';
This returns
"domainUserName" <- Browser
"domain\\UserName" <- Debugging
What I expect is
"domain\UserName" <- Browser
Any ideas?
Based on your comments you are using the following code to show the user name:
alert('#HttpContext.Current.User.Identity.Name');
#HttpContext.Current.User.Identity.Nameis a string that can contain "\" backslash character. This character is considered as a escape character in javascript as it is in C# as well.
You need to escape the "\" character in the string before passing it to Javascript like that:
alert('#HttpContext.Current.User.Identity.Name.Replace("\\", "\\\\")')

How to show String new lines on gsp grails file?

I've stored a string in the database. When I save and retrieve the string and the result I'm getting is as following:
This is my new object
Testing multiple lines
-- Test 1
-- Test 2
-- Test 3
That is what I get from a println command when I call the save and index methods.
But when I show it on screen. It's being shown like:
This is my object Testing multiple lines -- Test 1 -- Test 2 -- Test 3
Already tried to show it like the following:
${adviceInstance.advice?.encodeAsHTML()}
But still the same thing.
Do I need to replace \n to or something like that? Is there any easier way to show it properly?
Common problems have a variety of solutions
1> could be you that you replace \n with <br>
so either in your controller/service or if you like in gsp:
${adviceInstance.advice?.replace('\n','<br>')}
2> display the content in a read-only textarea
<g:textArea name="something" readonly="true">
${adviceInstance.advice}
</g:textArea>
3> Use the <pre> tag
<pre>
${adviceInstance.advice}
</pre>
4> Use css white-space http://www.w3schools.com/cssref/pr_text_white-space.asp:
<div class="space">
</div>
//css code:
.space {
white-space:pre
}
Also make a note if you have a strict configuration for the storage of such fields that when you submit it via a form, there are additional elements I didn't delve into what it actually was, it may have actually be the return carriages or \r, anyhow explained in comments below. About the good rule to set a setter that trims the element each time it is received. i.e.:
Class Advice {
String advice
static constraints = {
advice(nullable:false, minSize:1, maxSize:255)
}
/*
* In this scenario with a a maxSize value, ensure you
* set your own setter to trim any hidden \r
* that may be posted back as part of the form request
* by end user. Trust me I got to know the hard way.
*/
void setAdvice(String adv) {
advice=adv.trim()
}
}
${raw(adviceInstance.advice?.encodeAsHTML().replace("\n", "<br>"))}
This is how i solve the problem.
Firstly make sure the string contains \n to denote line break.
For example :
String test = "This is first line. \n This is second line";
Then in gsp page use:
${raw(test?.replace("\n", "<br>"))}
The output will be as:
This is first line.
This is second line.

Groovy- searching and excretion xml code from log file

I have so many texts in log file but sometimes i got responses as a xml code and I have to cut this xml code and move to other files.
For example:
sThread1....dsadasdsadsadasdasdasdas.......dasdasdasdadasdasdasdadadsada
important xml code to cut and move to other file: <response><important> 1 </import...></response>
important xml code to other file: <response><important> 2 </important...></response>
sThread2....dsadasdsadsadasdasdasdas.......dasdasdasdadasdasdasdadadsada
Hindrance: xml code starting from difference numbers of sign (not always start in the same number of sign)
Please help me with finding method how to find xml code in text
Right now i tested substring() method but xml code not always start from this same sign :(
EDIT:
I found what I wanted, function which I searched was indexOf().
I needed a number of letter where String "Response is : " ending: so I used:
int positionOfXmlInLine = lineTxt.indexOf("<response")
And after this I can cut string to the end of the line :
def cuttedText = lineTxt.substring(positionOfXmlInLine);
So I have right now only a XML text/code from log file.
Next is a parsing XML value like BDKosher wrote under it.
Hoply that will help someone You guys
You might be able to leverage XmlSlurper for this, assuming your XML is valid enough. The code below will take each line of the log, wrap it in a root element, and parse it. Once parsed, it extracts and prints out the value of the <important> element's value attribute, but instead you could do whatever you need to do with the data:
def input = '''
sThread1..sdadassda..sdadasdsada....sdadasdas...
important code to cut and move to other file: **<response><important value="1"></important></response>**
important code to other file: ****<response><important value="3"></important></response>****
sThread2..dsadasd.s.da.das.d.as.das.d.as.da.sd.a.
'''
def parser = new XmlSlurper()
input.eachLine { line, lineNo ->
def output = parser.parseText("<wrapper>$line</wrapper>")
if (!output.response.isEmpty()) {
println "Line $lineNo is of importance ${output.response.important.#value.text()}"
}
}
This prints out:
Line 2 is of importance 1
Line 3 is of importance 3

Issue with using int.parse() in Dart

I'm currently teaching myself the Dart language, and my first app doesn't seem to be working right. Here's the code that's causing trouble:
usrLoc = int.parse(query("#txtLoc").text);
When I try to run the app, it opens fine, but when I click the button that triggers this (and three other similar parses), the debugger stops and tells me "Source not found" for int._native_parse(), int._parse(), and int.parse().
Any help would be greatly appreciated.
The text property for the specified element #txtLoc returns an empty string.
The parse method requires that:
The source must be a non-empty sequence of base- radix digits, optionally prefixed with a minus or plus sign ('-' or '+').
You can specify an onError named argument in your call to parse, which takes a callback that handles the invalid input. E.g., if you want the parse call to return the value 42 for all invalid input, you can do this:
usrLoc = int.parse(query("#txtLoc").text, onError: (val) => 42);
If you really expect the element to have some text, you can store the result of query("#txtLoc").text into a separate variable and verify the value. It would also be interesting to check what the real element type is or which tag is marked with id #txtLoc.
If you want to get the content of an input element, you should use the value property instead of text:
query("#txtLoc").value

Resources