read string between two double quote php - php

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.

Related

XML tagname is a PHP function

I'm trying to parse an XML file in PHP with the simplexml_load_file function. Everything is fine, except my XML file has a <TIME> tag, which is a PHP function.
So the following code fails to get the tag value :
$xml = simplexml_load_file('some_xml_file.xml');
$value = $xml->SOME_TAG->TIME;
How do I get this value?
From the PHP manual:
Accessing elements within an XML document that contain characters not
permitted under PHP's naming convention (e.g. the hyphen) can be
accomplished by encapsulating the element name within braces and the
apostrophe.
Example #3 Getting
<?php
include 'example.php';
$xml = new SimpleXMLElement($xmlstr);
echo $xml->movie->{'great-lines'}->line; // "PHP solves all my web problems"
?>
And if you need to get an attribute you can do this:
So far, we have only covered the work of reading element names and
their values. SimpleXML can also access element attributes. Access
attributes of an element just as you would elements of an array.
foreach ($xml->movie[0]->rating as $rating) {
switch((string) $rating['type'])
This works for me
<?php
$xmlString = "<top><middle><TIME>1:27</TIME></middle></top>";
$xml = simplexml_load_string($xmlString);
echo $xml->middle->TIME;
php /tmp/xml.php
1:27
Check the contents of your XML file. For your PHP code to work, it should AT LEAST contain this:
<XML>
<SOME_TAG>
<TIME>1:27</TIME>
</SOME_TAG>
</XML>
When I use this XML file combined with your code, it works as expected.
Thanks everyone, I manage to get the value but there's still something strange.
XML example :
<INGREDIENTS>
<INGREDIENT>
<NAME>Potatoes</NAME>
<AMOUNT>10 kg</AMOUNT>
<TME>20 min</TIME>
</INGREDIENT>
</INGREDIENTS>
PHP code to get NAME, AMOUNT and TIME values :
$ing = $xml->INGREDIENTS->INGREDIENT;
$name = $ing->NAME;
$amount= $ing->AMOUNT;
$time= $ing->TIME;
echo $name." / ".$amount." / ".$time;
Result :
Potatoes / 10 kg /
However, if I use the whole path to the TIME tag :
$ing = $xml->INGREDIENTS->INGREDIENT;
$name = $ing->NAME;
$amount= $ing->AMOUNT;
$time= $xml->INGREDIENTS->INGREDIENT->TIME;
echo $name." / ".$amount." / ".$time;
Result :
Potatoes / 10 kg / 20 min
Can anyone explain why it's working this way ?

SimpleXMLElement using a string

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.

Ampersands in database

I am trying to write a php function that goes to my database and pulls a list of URLS and arranges them into an xml structure and creates an xml file.
Problem is, Some of these urls will contain an ampersand that ARE HTML encoded. So, the database is good, but currently, when my function tries to grab these URLS, the script will stop at the ampersands and not finish.
One example link from database:
http://www.mysite.com/myfile.php?select=on&league_id=8&sport=15
function buildXML($con) {
//build xml file
$sql = "SELECT * FROM url_links";
$res = mysql_query($sql,$con);
$gameArray = array ();
while ($row = mysql_fetch_array($res))
{
array_push($row['form_link']);
}
$xml = '<?xml version="1.0" encoding="utf-8"?><channel>';
foreach ($gameArray as $link)
{
$xml .= "<item><link>".$link."</link></item>";
}
$xml .= '</channel>';
file_put_contents('../xml/full_rankings.xml',$xml);
}
mysql_close($con);
session_write_close();
If i need to alter the links in the database, that can be done.
You can use PHP's html_entity_decode() on the $link to convert & back to &.
In your XML, you could also wrap the link in <![CDATA[]]> to allow it to contain the characters.
$xml .= "<item><link><![CDATA[" . html_entity_decode($link) . "]]></link></item>";
UPDATE
Just noticed you're actually not putting anything into the $gameArray:
array_push($row['form_link']);
Try:
$gameArray[] = $row['form_link'];
* #Musa looks to have noticed it first, for due credit.
Look at this line
array_push($row['form_link']);
you never put anything in the $gameArray array, it should be
array_push($gameArray, $row['form_link']);
You need to use htmlspecialchars_decode. It will decode any encoded special characters in string passed to it.
This is most likely what you are looking for:
http://www.php.net/manual/en/function.mysql-real-escape-string.php
Read the documentation, there are examples at the bottom of the page...
'&' in oracleSQL and MySQL are used in queries as a logical operator which is why it is tossing an error.
You may also want to decode the HTML...

php code inside variable with html code

I want to add code php to variable with html, for example
$html = '<b></b> <?php echo $lang["text"] ?>';
but it don't interpret php code. What am I doing wrong?
Use string concatenations like this:
$html = '<b></b>' . $lang['text'];
or insert variable in double quoted string like this:
$html = "<b></b>${lang['text']}";
both versions are correct, use the one that you like.
What you want is called string interpolation (read about how it works for PHP).
Your particular example would be solved using
$html = "<b></b> {$lang['text']}";
String interpolation only happens in double quoted string ("string here").
its very important to escape the output. (security basics)
$html = sprintf('<b>%s</b>', htmlspecialchars($lang['text']));
You can't switch from "Output raw text mode" to "Run PHP code mode" in the middle of a string while you are already in "Run PHP code mode"
$html = "<b></b> ${lang['text']}";
… although why you want an empty bold element is beyond me.
<?php
$html = '<b>'.$lang['text'].'</b>';
?>
make sure file extension is php.
<?php
$html = '<b>' . $lang["text"] . '</b>';
?>

identify and execute php code on a string

I would like to know if it's possible to execute the php code in a string. I mean if I have:
$string = If i say <?php echo 'lala';?> I wanna get "<?php echo 'dada'; ?>";
Does anybody knows how?
[EDIT] It looks like nobody understood. I wanna save a string like
$string = If i say <?php count(array('lala'));?>
in a database and then render it. I can do it using
function render_php($string){
ob_start();
eval('?>' . $string);
$string = ob_get_contents();
ob_end_clean();
return $string;
}
The problem is that I does not reconize php code into "" (quotes) like
I say "<?php echo 'dada'; ?>"
$string = ($test === TRUE) ? 'lala' : 'falala';
There are lots of ways to do what it looks like you're trying to do (if I'm reading what you wrote correctly). The above is a ternary. If the condition evaluates to true then $string will be set to 'lala' else set to 'falala'.
If you're literally asking what you wrote, then use the eval() function. It takes a passed string and executes it as if it were php code. Don't include the <?php ?> tags.
function dropAllTables() {
// drop all tables in db
}
$string = 'dropAllTables();';
eval($string); // will execute the dropAllTables() function
[edit]
You can use the following regular expression to find all the php code:
preg_match_all('/(<\?php )(.+?)( \?>)/', $string, $php_code, PREG_OFFSET_CAPTURE);
$php_code will be an array where $php_code[0] will return an array of all the matches with the code + <?php ?> tags. $php_code[2] will be an array with just the code to execute.
So,
$string = "array has <?php count(array('lala')); ?> 1 member <?php count(array('falala')); ?>";
preg_match_all('/(<\?php )(.+?)( \?>)/', $string, $php_code, PREG_OFFSET_CAPTURE);
echo $php_code[0][0][0]; // <?php count(array('lala')); ?>
echo $php_code[2][0][0]; // count(array('lala'));
This should be helpful for what you want to do.
Looks like you are trying to concatenate. Use the concatenation operator "."
$string = "if i say " . $lala . " I wanna get " . $dada;
or
$string = "if i say {$lala} I wanna get {$dada}.";
That is what I get since your string looks to be a php variable.
EDIT:
<?php ?> is used when you want to tell the PHP interpreter that the code in those brackets should be interpreted as PHP. When working within those PHP brackets you do not need to include them again. So as you would just do this:
// You create a string:
$myString = "This is my string.";
// You decide you want to add something to it.
$myString .= getMyNameFunction(); // not $myString .= <?php getMyNameFunction() ?>;
The string is created, then the results of getMyNameFunction() are appended to it. Now if you declared the $myString variable at the top of your page, and wanted to use it later you would do this:
<span id="myString"><?php echo $myString; ?></span>
This would tell the interpreter to add the contents of the $myString variable between the tags.
Use token_get_all() on the string, then look for a T_OPEN_TAG token, start copying from there, look for a T_CLOSE_TAG token and stop there. The string between the token next to T_OPEN_TAG and until the token right before T_CLOSE_TAG is your PHP code.
This is fast and cannot fail, since it uses PHP's tokenizer to parse the string. You will always find the bits of PHP code inside the string, even if the string contains comments or other strings which might contain ?> or any other related substrings that will confuse regular expressions or a hand-written, slow, pure PHP parser.
I would consider not storing your PHP code blocks in a database and evaluating them using eval. There is usually a better solution. Read about Design Pattern, OOP, Polymorphism.
You could use the eval() function.

Categories