This question already has answers here:
How to parse XML with unescaped ampersand
(2 answers)
Closed 2 years ago.
I am trying upload xml file using simplexml_load_file but when in file is special character i'm getting an error ( There is everything alright without special character in it).
First of all, I am using XML file from another program so i can't change it.
This is sample of xml:
<wuo>
<header>
<title>title1</title>
</header>
<body>
<lp>1</lp>
<sign>124.455</sign>
<text>sample text with & character</text> //<-- this is causing the problem
</body>
<body>
<lp>2</lp>
<sign>12556.455</sign>
<text>sample text 2</text>
</body>
</wuo>
My code:
if(isset($_POST["submit"]))
{
if(isset($_FILES['wuo']) && ($_FILES['wuo']['error'] == UPLOAD_ERR_OK))
{
if(!simplexml_load_file($_FILES['wuo']['tmp_name']))
{
// if file has special character in it this fires up
echo 'Error';
}
else
$file = simplexml_load_file($_FILES['wuo']['tmp_name']);
print_r($file);
/**
showing file to html etc... unimportant code for this case
**/
}
else
echo 'Error:' . $_FILES['wuo']['error'];
}
I know, I should do something before simplexml_load_file but i don't know what exaclty. Or maybe I should use something else...
Btw: I don't need to secure it because this is only for me.
Your XML is not valid. An ampersand must be escaped as &.
If you can't change it yourself, you will need to pre-process it in some way before passing it to an XML parser.
Related
This question already has answers here:
Regular expression for parsing CSV in PHP
(6 answers)
Closed 8 years ago.
I have a text file (similar to CSV concept) to parse and load into different columns.
I receive it from an external application I can't modify.
It uses ";" as field separator but unfortunatly we can have the same char also inside some content.
Here a little sample:
Code;Name;Address;E_mail;Contact name
000001;FUTURAMA SNC;VIA BARBAPAPA, 1;info#gmail.com;matteo futuro;
000006;FERRANTIBUS SRL;VIA TOPOLINO, 1;amministrazione#gmail.com;nicola ferri;
000008;MORMORO SPA;VIA CICCETTI, 30;"cri#mormoro.it; rossi#mormoro.it";panebianco gianpietro;
we use this code to parse the file
$file = fopen("C:\\wamp\\www\\testcsv\\customers.csv","r");
$result ="";
$i=0;
while(! feof($file))
{
$result[$i++]= fgets($file);
}
for($j=1;$j<count($result);$j++){
$tempData = preg_split("/[;]/",$result[$j]);
print_r( $tempData );
}
as you can see, in the last line of the sample file, we have ";" char inside email field.... so it is read as another column separator and in the third record the email field is splitted as 2 column, with the result I have an additional column.
Is there any way, using regular expression to skip ; char if it is inside the "" chars?
Thanks in advance for the help
You should not use regexpr to parse CSV files.
Use native PHP function http://php.net/manual/en/function.fgetcsv.php
This will solve your problem.
This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
So I'm trying to define $picurl1 so that it uses the value in $pic1. So in the end I want it to be:
<img src="./pictures/{definition of pic1}.png">
Right now I use this php code:
$pic1 = '<script src="pic.js"></script>';
$picurl1 = '<img src="./pictures/' + $pic1 + '.png'">';
Sorry if I'm not being very clear. I don't really know how to explain it. I hope you understand.
In other words, please tell me what I should change $picurl1 to.
By the way the script comes up with a random picture name without the '.png'.
Thanks in advance.
For starters, you're using the wrong operator to concatenate strings in PHP. I think you mean this:
$picurl1 = '<img src="./pictures/' . $pic1 . '.png'">';
More to the point, what is "definition of pic1"? Do you mean that the code in pic.js will randomly choose a file name, and you want its result to be the URL used in the img tag?
The problem you're encountering, then, is that PHP runs on the server while JavaScript runs on the client. So your PHP code can't use the result of pic.js because it won't have a result until the browser runs it, after the PHP code is done.
So you need to get that result client-side in JavaScript code.
How does pic.js create that result? That is, is there a function in pic.js? For now I'm going to assume there is, and I'm going to assume that function is called something like getFileName. (Just for the purpose of this example.)
After you included the JavaScript code, and after the img tag is in the document, you can call that function and set the src of the img tag to its results. To help us identify the img tag, let's give it an id:
<img src="default.gif" id="theImage" alt="This is a dynamic image" />
(I gave it a default value for the src since an empty value is invalid. I also have it an alt value for completeness.) To change its src value to the result of a function, you'd do something like the following:
document.getElementById('theImage').src = getFileName();
Remember, this is all client-side code. The only way you can use the "result" in PHP code is if the calculation is done in PHP, not in JavaScript.
You must consider that all the server side codes are executed before the client side codes (javascript, html, css , ...). so your code does not make any sense , you can not embed an undefined code inside another code that is executing sooner.
if your js code must return some thing, so remove php codes and simply use HTML instead
I tested this successfully:
$picName = "greenButterfly7"; //note no spaces inbetween green and butterfly
$picurl1 = "<img src='./pictures/" . $picName . ".png'>";
echo $picurl1;
or in pure HTML form:
<img src='pictures/greenButterfly7.png'>
or in embedded form (PHP inside HTML):
<img src='pictures/<?php echo $picName; ?>.png'>
Edit: I think %27 is actually the wrong kind of quote. I am still stuck though, I cannot find a PHP function that does the conversion I want.
Edit (again): I found a solution where I stick %26rsquo%3bs into the URL and it turns into ’. It works so I posted it as an answer below but I'd still be interested in knowing how it'd be done with PHP functions.
I'm working on a website that uses a PHP tree as if it were a directory. For example, if someone types index.php?foo=visual programming (or index.php?foo=visual%20programming) then the website opens the item "Visual Programming" (I'm using strtolower()).
Another working example would be index.php?foo=visual programming&bar=animated path finder which opens "Animated Path Finder", a child of "Visual Programming".
The problem is that some of the items are named things like "Conway’s Game of Life" which uses a HTML entity. My guess of what someone should type to open this would be index.php?foo=visual%20programming&bar=conway%27s%20game%20of%20life. The problem is that ' is not === to ’.
What do I need to do to make this work? Here is my code that selects an item based on $_GET (the PHP is inside of <script type="text/javascript">):
<?php
function echoActiveDirectory($inTree) {
// Compare $_GET with PhpTree
$itemId = 0;
foreach ($_GET as $name) {
if ($inTree->children !== null) {
foreach ($inTree->children as $child) {
if (strtolower($child->title) === strtolower($name)) {
$itemId = $child->id;
$inTree = $child;
break;
}
}
}
}
// Set jsItems[$itemId].selected(), it will be 0 if nothing was found
echo "\t\tjsItems[".$itemId."].selected();\n";
}
echo "// Results of PHP echoActiveDirectory(\$root)\n";
echoActiveDirectory($root);
?>
The website is a work in progress, but it can be tested here to see $_GET working: http://alexsimes.com/index.php
The hex code %27 (39 decimal) will never translate to ’, since it is a completely different entity (Wikipedia). It could be translated to ', but PHP doesn't do that (although I don't know the reason for that).
Edit
While there is no standard for URL-encoding multibyte character sets, PHP will treat a string as just a set of bytes, and if those match an UTF-8 sequence, it will work:
php -r 'echo htmlentities(urldecode("%E2%80%99"), ENT_QUOTES|ENT_HTML401);'
should output
’
You can use html_entity_encode() and html_entity_decode() PHP functions to convert those characters to html entities or decode them back to desired characters before comparison.
You can try the htmlentities function to convert special characters to corresponding html entity. But in your case if data is already stored in db as html entity form, the data from $_GET parameter must be first passed through htmlentities before using it in your query.
This question already has an answer here:
How can we include php tag in html with php echo [closed]
(1 answer)
Closed 10 years ago.
I already post this question before but people always ask unnecessary question. I'm gonna explain it in a simple way.
I HAVE 3 files :
a php file (contains only html, thats important) : We call it X file for the example.
a php file where there's some database query to insert database data on the screen : Y file
a php file (a script that will make some manipulations) : Z file
SO, i want to include Y into X with the script of Z.
In Z, i make a str_replace($text, $new, file_get_contents($file));
The ONLY THING is that i need to include PHP open and close TAGS in X because there's no php tags in it.
So, $new = "<?php include('Y.php'); ?>";.
If you try, the close tag wont be considered in the string, but that's what i want.
Hope this question is NOW clear. I can't be more clearer than that. :D
Thanks for you advice.
To include a file you do
<?php
include(file);
?>
So in this case
X contains <?php include('Y'); ?> And Y contains <?php include('Z') ?>
But if you are doing what i think you are doing (a template of some sort) you would be better of by looking into overflow buffer ( ob_start and ob_end_flush for example )
Those can place all echoed information into a variable to be modified later, also the php inside is run, instead of just read as text as in your example with the file_get_contents()
The question is very unclear and vague, but I have a guess:
File X is some HTML where you want to replace special markers.
File Y loads the value from DB that should replace the marker.
File Z does the replacement.
This could be solved like that (File Z):
<?php
ob_start();
include("Y.php");
$repl = ob_get_contents();
ob_end_clean();
ob_start();
include("X.php");
$src = ob_get_contents();
ob_end_clean();
echo str_replace("THEREPLACEMENTMARKER", $repl, $src);
?>
I wrote a php script that pulls some data from a database and displays it in XML format. For some reason it halts output when it gets to an apostrophe in the data. This is a SELECT statement, and a simple one at that, so I don't understand why there are any issues with apostrophes or quotation marks. I've tried using addslashes() and mysql_real_escape_string(), even though my understanding is that those are for sanitizing data being inserted into the database, and it did not help. I'm stumped. Below is the code and thanks in advance for any advice!
<? if($result = $mysqli->query("SELECT * FROM ".$tbl)){
while($row = $result->fetch_object()){ ?>
<slide>
<id><?= $row->id ?></id>
<title><?= $row->title ?></title>
<chatter><?= $row->description ?></chatter>
<image><?= $row->path ?></image>
<link><?= $row->href ?></link>
<active><?= $row->active ?></active>
</slide>
<? }
}else{
echo $mysqli->error;
}
EDIT:
It turns out I have misunderstood the problem. They are not apostrophes but instead are right single quotes. If I change them to actual apostrophes the script works but I still don't understand why it doesn't simply output them though.
Try with str_replace("'", "\'", $field_to_be_replaced);
You can replace the ' char with a blank space if you prefer, just for testing.
Are you sure it halts on the output of the data, and not when the data is processed? Apostrophe's have special meaning in XML, so if they are included in your XML data you have to replace them with an entity reference. There are 5 predefined entity references in XML, for less than, greater than, ampersand, apostrophe, and one for quotation mark. Alternatively, you can mark the text as CDATA so that the XML parser doesn't try to parse it.
Try making your program output the XML data to a text file instead of to wherever it is going now. Does it still halt on the apostrophe? If not, then it's definitely because of a problem parsing the data. If your program still halts on the apostrophe even when outputting the data only to a text file, there may be a problem somewhere else in the program where that data is processed. Check all the references to the variable containing the data, and see if you can find the exact line the program breaks on.
the apostrophe (') is an invalid character for XML!
You must call $safe_string = str_replace("'","'",$string) in all your fields before
outputting the .XML file.
Check here to learn about these characters and build a more complete str_replace
EDIT:
What im using:
// save ubercart products in XML
function replace_characters_for_xml($str) {
return str_replace(
array("&",">","<","'",'"'),
array("&",">","<","'","""),$str
);
}
...
$row->title = replace_character_for_xml($row->title);
$row->href = replace_character_for_xml($row->href);
...