I want to create a new SimpleXMLElement with data . When I put the data from the link below in the code I get the next error: Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML
The encoded data can be found here:http://www.interwebmedia.nl/dataxi/base64.txt
decoded data: http://www.interwebmedia.nl/dataxi/data.txt
<?php
str = 'encodeddata';
//echo htmlspecialchars(base64_decode($str),ENT_QUOTES);
$decoded = htmlspecialchars(base64_decode($str),ENT_QUOTES);
$xml = new SimpleXMLElement($decode);
echo $xml->asXML();
?>
I think you've attempted to use HEREDOC syntax (or seen somebody else using it) but completely misunderstood it.
HEREDOC syntax is an alternative way of quoting a string, instead of " or '. It's useful for hard-coding blocks of XML, because it acts like double-quotes, but let's you use double-quotes inside, like this:
$my_xml_string = <<<XML
<some_xml>
<with multiple_lines="here" />
</some_xml>
XML;
That code is precisely equivalent to this:
$my_xml_string = "
<some_xml>
<with multiple_lines=\"here\" />
</some_xml>
";
What you have done instead is taken the literal string "<<<" and added it onto your XML, giving you a string like this:
$my_xml_string = "<<<XML
<some_xml>
<with multiple_lines=\"here\" />
</some_xml>
XML";
Or in your example, the string "<<<XML<data>XML".
As far as the XML parser's concerned, you've just put a load of garbage on the beginning and end of the string, so it rightly complains it's not a valid XML document.
Related
I have a big JSON code - 2 801 278 characters. Now I want to create an array from this JSON code in my PHP script, but I can't because my script has quotes and double quotes and PHP return an error. Here is a simply code which do the same problem:
{"title":"Example string's with \"special\" characters"}
As you can see, when I paste this code in that way:
var_dump(json_decode('{"title":"Example string's with \"special\" characters"}', true));
I got an error because ' is not escaped. When I try to change change string's for string\'s, I got:
Recoverable fatal error: Object of class stdClass could not be
converted to string in...
How I should change this JSON code to correctly create an array?
You can do one of two things.
Read JSON from a file. (Recommended)
Use Heredoc.
Reading JSON from a File
Have a file next to your PHP file that has the JSON and read it using file_get_contents().
<?php
$json = file_get_contents("file.json");
$array = json_decode($json, true);
?>
Using Heredoc
<?php
$json = <<<EOD
{"title":"Example string's with \"special\" characters"}
EOD;
$array = json_decode($json, true);
?>
Demo: https://eval.in/1119967
Both the above methods yield the same output.
I have an xml string. That xml string has to be converted into PHP array in order to be processed by other parts of software my team is working on.
For xml -> array conversion i'm using something like this:
if(get_class($xmlString) != 'SimpleXMLElement') {
$xml = simplexml_load_string($xmlString);
}
if(!$xml) {
return false;
}
It works fine - most of the time :) The problem arises when my "xmlString" contains something like this:
<Line0 User="-5" ID="7436194"><Node0 Key="<1" Value="0"></Node0></Line0>
Then, simplexml_load_string won't do it's job (and i know that's because of character "<").
As i can't influence any other part of the code (i can't open up a module that's generating XML string and tell it "encode special characters, please!") i need your suggestions on how to fix that problem BEFORE calling "simplexml_load_string".
Do you have some ideas? I've tried
str_replace("<","<",$xmlString)
but, that simply ruins entire "xmlString"... :(
Well, then you can just replace the special characters in the $xmlString to the HTML entity counterparts using htmlspecialchars() and preg_replace_callback().
I know this is not performance friendly, but it does the job :)
<?php
$xmlString = '<Line0 User="-5" ID="7436194"><Node0 Key="<1" Value="0"></Node0></Line0>';
$xmlString = preg_replace_callback('~(?:").*?(?:")~',
function ($matches) {
return htmlspecialchars($matches[0], ENT_NOQUOTES);
},
$xmlString
);
header('Content-Type: text/plain');
echo $xmlString; // you will see the special characters are converted to HTML entities :)
echo PHP_EOL . PHP_EOL; // tidy :)
$xmlobj = simplexml_load_string($xmlString);
var_dump($xmlobj);
?>
Update: Casting as an array does the trick. See this response, since I don't have enough clout to upvote :)
I started on this problem with many potential culprits, but after lots of diagnostics the problem is still there and no obvious answers remain.
I want to print the placename "Gaborone", which is located at the first tag under the first tag under the first tag of this API-loaded XML file. How can I parse this to return that content?
<?php
# load the XML file
$test1 = (string)file_get_contents('http://www.afdb.org/fileadmin/uploads/afdb/Documents/Generic-Documents/IATIBotswanaData.xml');
#throw it into simplexml for parsing
$xmlfile = simplexml_load_string($test1);
#output the parsed text
echo $xmlfile->iati-activity[0]->location[0]->gazetteer-entry;
?>
Which never fails to return this:
Parse error: syntax error, unexpected '[', expecting ',' or ';'
I've tried changing the syntax to avoid the hyphens in the tag names as such:
echo $xmlfile["iati-activity"][0]["location"][0]["gazetteer-entry"];
. . . but that returns complete nothingness; no error, no source.
I've also tried debugging based on these otherwise-helpful threads, but none of the solutions have worked. Is there an obvious error in my simplexml addressing?
I've tried changing the syntax to avoid the hyphens in the tag names
as such: echo
$xmlfile["iati-activity"][0]["location"][0]["gazetteer-entry"];
Your problem here is that, object native casting to an array isn't recursive, so that you did that for primary keys only. And yes, your guess is correct - you shouldn't deal with object properties when working with returned value of simplexml_load_string() because of the syntax issues. Instead, you should cast a returned value of it (stdclass) into an array recursively. You can use this function for that:
function object2array($object) {
return json_decode(json_encode($object), true);
}
The rest:
// load the XML file
$test1 = file_get_contents('http://www.afdb.org/fileadmin/uploads/afdb/Documents/Generic-Documents/IATIBotswanaData.xml');
$xml = simplexml_load_string($test1);
// Cast an object into array, that makes it much easier to work with
$data = object2array($xml);
$data = $data['iati-activity'][0]['location'][0]['gazetteer-entry']; // Works
var_dump($data); // string(8) "Gaborone"
I had a similar problem parsing XML using the simpleXML command until I did the following string replacements:
//$response contains the XML string
$response = str_replace(array("\n", "\r", "\t"), '', $response); //eliminate newlines, carriage returns and tabs
$response = trim(str_replace('"', "'", $response)); // turn double quotes into single quotes
$simpleXml = simplexml_load_string($response);
$json = json_decode(json_encode($simpleXml)); // an extra step I took so I got it into a nice object that is easy to parse and navigate
If that doesn't work, there's some talk over at PHP about CDATA not always being handled properly - PHP version dependent.
You could try this code prior to calling the simplexml_load_string function:
if(strpos($content, '<![CDATA[')) {
function parseCDATA($data) {
return htmlentities($data[1]);
}
$content = preg_replace_callback(
'#<!\[CDATA\[(.*)\]\]>#',
'parseCDATA',
str_replace("\n", " ", $content)
);
}
I've reread this, and I think your error is happening on your final line - try this:
echo $xmlfile->{'iati-activity'}[0]->location[0]->{'gazetteer-entry'};
good day, I have a UML class diagram exported to an XML file, and the code basically and repeatedly is like this:
<UML:Class name="Zip Code" isLeaf="false" xmi.id="{C7C65474-DD51-4165-89A0-FB552A929185}" isAbstract="false" visibility="public">
So, what i need to do, is to output to the user all the class(etc) found in the file.
More exactly, i need to read the name inside the double quotes.
More properly, read the string inside the double quotes from a specific tag, example:
to get all classes names i must search in: <UML:Class name=" STRING WHAT I WANNA GET "
to get all atributtes names i must search in: <UML:Attribute name=" STRING I WANNA GET "
edit : i have tried but sttil not working :x
i have this;
example.php
<?php
$xmlstr = <<<XML
<UML:Class name="Colaborator" isLeaf="false" xmi.id="{B8D626AE-F100-4548-9136-057E68BE577D}" isAbstract="false" visibility="public">
<UML:Classifier.feature>
<UML:Attribute name="Colaborator Name" xmi.id="{BB9111A8-740A-4463-9DF8-719E21E3F1CC}" ownerScope="instance" visibility="private" changeability="changeable">
<UML:StructuralFeature.type>
<UML:Classifier xmi.idref="Dttp0"/>
<UML:lol> sfdsf </UML:lol>
</UML:StructuralFeature.type>
</UML:Attribute>
<UML:Attribute name="Colaborator Address" xmi.id="{D7C15DA3-F86B-4696-874C-C69F94CDEE51}" ownerScope="instance" visibility="private" changeability="changeable">
<UML:StructuralFeature.type>
<UML:Classifier xmi.idref="Dttp1"/>
</UML:StructuralFeature.type>
</UML:Attribute>
</UML:Classifier.feature>
</UML:Class>
XML;
?>
and in test.php
<?php
include 'example.php';
$UML:Class = new SimpleXMLElement($xmlstr);
foreach ($UML:Class->xpath('//UML:Attribute') as $attr) {
echo $attr->name, PHP_EOL;
}
?>
If you just need the name (and perhaps offset):
regex: name="([\w ]+)"
Otherwise, you'll need to use an XML parser.
Is there a helper function that will properly escape a string to be rendered as a single quote quoted JavaScript string literal?
I know of jsQuoteEscape but it only handles quotes and does not treat \n & \r etc.
so if my string is 'line1\nlineb' (i.e. two lines with a newline between them)
and I use
var jsvar='<?php echo $this->helper('myextension')->jsQuoteEscape($mystring); ?>';
I will get in the rendered content
var jsvar='line1
line2';
which is a syntax error.
Thanks,
Eyal
Yes
$string = 'Hello
There';
var_dump( Mage::helper('core')->jsonEncode($string) );
var_dump( json_encode($string) );
I've never been clear if this encoding a non-object string datatypes as a javascript string is a side-effect of the JSON encoding, or if it's true, according to Hoyle Crockford JSON, so I always like to wrap my strings in an object when passing them around
$o = new stdClass();
$o->param = 'This is my
Param';
$json = json_encode($o);
echo 'var data = ' . $json . ';' . "\n";
echo 'var jsdata = data.param';
This is how you'd handle this with javascript. There's no method that's build specifically for this. If you're interested in seeing the helper methods you do have available from a block, checkout the methods in
app/code/core/Mage/Core/Block/Abstract.php
app/code/core/Mage/Core/Block/Template.php
and if you're dealing with a template that's part of a block higher up the chain, get its class and then check its definition
var_dump get_class($this);