I know i have bothered all of you with my questions but i have a question about php and xml
i am trying to store all the values of the pages in xml so i would create a multilingual website
after searching i have got to a way but and i tried to alter it a little bit
there is my xml files:
en.xml:
<?xml version="1.0" encoding="UTF-8"?>
<main>
<!--Page Titles-->
<freeEaHdr>
<![CDATA[Get in the game!]]>
</freeEaHdr>
<freeEaSubhdr>
<![CDATA[Load up your Xperia™ PLAY with 4 exciting EA titles for<span style="color:#ff9c00;"> FREE</span>]]>
</freeEaSubhdr>
<!--Page Titles-->
</main>
and there is my ar.xml
<?xml version="1.0" encoding="UTF-8"?>
<main>
<!--Page Titles-->
<freeEaHdr>
<![CDATA[ادخل اللعبة]]>
</freeEaHdr>
<freeEaSubhdr>
<![CDATA[حمل الاكسبيريا الان]]>
</freeEaSubhdr>
<!--Page Titles-->
</main>
and i have created an select_lang.php
<?php
function select_lang(){
if(isset($_GET['lang'])){
$lang = $_GET['lang'];
if($lang == "en"){
$xml = simplexml_load_file("en.xml");
} else{
$xml = simplexml_load_file("ar.xml");
}
} else {
$xml = simplexml_load_file("en.xml");
}
return $xml;
}
?>
and the final page was index.php
<?php
include("select_lang.php");
select_lang();
?>
<div><?php echo $xml->freeEaHdr; ?></div>
<div><?php echo $xml-> freeEaSubhdr; ?></div>
english
arabic
now of course i get errors in index.php as for the main xml variable is not defined so if anybody has a solution
Thanks in advance
and sorry for bothering you
Your select_lang() function returns the created SimpleXML object $xml. You then try to use this object in your index.php file, but you haven't actually assigned the return value of select_lang() to anything.
Simply doing
$xml = select_lang();
instead of
select_lang();
will let you actually use the returned XML object in your index.php file.
try to:
<?php
include("select_lang.php");
$xml = select_lang(); //change this line
?>
Related
I have an xml file slider.xml with html code inside:
<?xml version="1.0" encoding="UTF-8"?>
<content>
<title>Slider</title>
<head>
<script async="async" src='ws-custom/plugins/slider.js'></script>
<script async="defer" src='ws-custom/plugins/functions.js'></script>
</head>
<footer>
<script async="defer" src='ws-custom/plugins/jquery.js'></script>
</footer>
</content>
In PHP I would like to:
1. load it (using simplexml, dom or other better solution) and store in a variable $xml;
2. create an array $head with both $xml->head->children();
3. return the original html code for $head[0] and $head[1].
I have tried using this code:
$xml = simplexml_load_file('slider.xml');
$head = $xml->head->children();
foreach($head as $element){
echo $element->asXML();
}
but it returns self-closing tags:
<script async="async" src="ws-custom/plugins/slider.js"/>
<script async="defer" src="ws-custom/plugins/functions.js"/>
which is not valid html code for W3C http://validator.w3.org/nu/
I would like also to be able to write only async, i.e.
because it's valid html, but with simplexml it's not valid xml.
Thank you very much.
Best regards.
I've edited the script, now it works perfectly.
Note please the row 6:
$element[] = null;
<?php
$xml = new DOMDocument();
$xml = simplexml_load_file('slider.xml');
$head = $xml->head->children();
foreach($head as $element){
$element[] = null;
echo $element->asXML().PHP_EOL;
}
SimpleXML can't output the empty tags properly, you should use DOMDocument instead (LIBXML_NOEMPTYTAG doesn't work in SimpleXML)...
$xml = new DOMDocument('1.0');
$xml->load("slider.xml");
$head = $xml->getElementsByTagName("head");
$headScripts= $head[0]->getElementsByTagName("script");
foreach($headScripts as $element){
echo $xml->saveXML($element, LIBXML_NOEMPTYTAG).PHP_EOL;
}
This code gets a start point (the <head> tag), as you only want the first one it uses [0] and finds the <script> tags inside the start point.
Which with the test source gives...
<script async="async" src="ws-custom/plugins/slider.js"></script>
<script async="defer" src="ws-custom/plugins/functions.js"></script>
I have this PHP function that pulls/extracts data from xml elements and displays them on my webpage. However it is only working when used with a local path. not from any external sources. Here is the code.
Index.php
<html>
<body>
<?php
include('render_xml_to_html.php');
// The internal path. DOES work.
render_xml_data('example.xml');
?>
</body>
</html>
Example.xml
<eveapi version="2"><currentTime>2014-05-08 03:34:23</currentTime>
<result>
<serverOpen>True</serverOpen>
<onlinePlayers>24957</onlinePlayers>
</result>
<cachedUntil>2014-05-08 03:35:58</cachedUntil>
</eveapi>
The function - render_xml_to_html.php
<?php
function render_xml_data($path_to_xml_file){
if (!file_exists($path_to_xml_file)){
return;
}else{
$chars_to_replace = array('[\r]','[\n]','[\t]');
$xmlstring = trim(preg_replace($chars_to_replace, '', file_get_contents($path_to_xml_file)));
}
$xml = new SimpleXMLElement($xmlstring);
foreach ($xml->result as $record) {
echo '<div class="record">'."\n";
echo '<h3>'.$record->onlinePlayers.'</h3>'."\n";
echo '</div><!--end record-->'."\n";
}
}
?>
The above code works as is. My issue is when I try to pull this info from the realtime .xml file on the hosts server. That url is:
https://api.eveonline.com/server/ServerStatus.xml.aspx/
When I replace example.xml with the above link it fails to work. So the following doe not work. Where I link to an external path rather than a local.
<?php
include('render_xml_to_html.php');
// The external path DOES NOT WORK
render_xml_data('https://api.eveonline.com/server/ServerStatus.xml.aspx/');
?>
Thanks in advance!
You can just use file_get_contents on this one, it can get the job done. Consider this example:
$url = 'https://api.eveonline.com/server/ServerStatus.xml.aspx/';
// access the url and get that file
$contents = file_get_contents($url);
// convert it to an xml object
$contents = simplexml_load_string($contents);
echo "<div class='record'>Number of Online Players: ".$contents->result->onlinePlayers."</div>";
Sample Output:
Number of Online Players: 23893
When I try to get values it doesn't seem to work. The xml file contains multiples of the same node <post> and I thought you could call a specific node like an array, but that doesn't seem to work. Below I have included the code.
File that gets xml values:
<?php
if(file_exists('settings.xml')){
$settings = simplexml_load_file('settings.xml');
$site_title = $settings->title;
$site_name = $settings->title;
$site_stylesheet = "css/main.css";
$theme_folder = "themes/".$settings->theme;
if(file_exists('posts.xml')){
$posts = simplexml_load_file('posts.xml');
$post = $posts->post[$_GET['post']];
$post_title = $post->title;
$post_content = $post->content;
$post_author = $post->author;
include($theme_folder."/header.php");
include($theme_folder."/post.php");
include($theme_folder."/footer.php");
} else {
exit("File \"posts.xml\" does not exist!");
}
} else {
exit("File \"settings.xml\" does not exist!");
}
?>
File that is included in the file above and uses the variables that the xml passes to:
<article>
<h1><?php echo $post_title ?></h1>
<?php echo $post_content ?>
<p><?php echo $post_author ?></p>
</article>
Xml file:
<?xml version="1.0" encoding="utf-8"?>
<posts>
<post>
<title>Hello World</title>
<author>tacticalsk8er</author>
<content>Hello world this is my blogging site</content>
</post>
<post>
<title>Hello Again</title>
<author>Nick Peterson</author>
<content><![CDATA[Hello Again world this is another test for my <b>blogging site</b>]]></content>
</post>
</posts>
Of course, you can access nodes in simplexml 'array-style':
$post = $xml->post[1]; // select second node
echo $post->title;
$xml represents the root-node <posts>, $xml->post selects posts/post.
see it working: http://3v4l.org/KOiv2
see the manual: http://www.php.net/manual/en/simplexml.examples-basic.php
<?php
include "../music/php/logic/core.php";
include "../music/php/logic/settings.php";
include "../music/php/logic/music.php";
$top = "At world's end";
// create doctype
$dom = new DOMDocument("1.0");
header("Content-Type: text/xml");
?>
<music>
<?php $_xml = "<title>".$top."</title>";
echo $_xml; ?>
</music>
I'm using this code to generate a dynamic XML document. The file is saved as PHP.
My problem is that I can't echo php variables into the xml. However I can echo "literal" type text. I can't see anything wrong with my approach, it just doesn't work!
I'm pretty new to XML so I've probably missed something glaringly simple.
I've also tried lines like:
<title><?php echo $top; ?></title>
You don't use DOM this way. You use the DOM API to create the entire document:
$doc = new DOMDocument();
$books = $doc->createElement( "books" );
$doc->appendChild( $books );
// ...
See:
http://www.ibm.com/developerworks/library/os-xmldomphp/
http://www.tonymarston.net/php-mysql/dom.html
https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6141415.html
A more verbose example (generating XHTML with DOM)
// Create head element
$head = $document->createElement('head');
$metahttp = $document->createElement('meta');
$metahttp->setAttribute('http-equiv', 'Content-Type');
$metahttp->setAttribute('content', 'text/html; charset=utf-8');
$head->appendChild($metahttp);
See this tutorial on how to use DOM for XHTML. For reuse of code, you can write your own classes extending DOM classes to get configurable components.
If you don't want to use DOM or want to use plain text for generating the XML, just approach it like any other template, e.g.
<root>
<albums>
<album id="<?php echo $albumId; ?>">
<title><?php echo $title; ?></title>
... other elements ...
</album>
</albums>
</root>
You can store your XMl string in a .php file then render it to get final formatted XMl string. In many cases simpler than playing with XMl writers
File template.php
<root>
<albums>
<album id="<?php echo $data['albumId']; ?>">
<title><?php echo $data['title']; ?></title>
... other elements ...
</album>
</albums>
</root>
Render
function render($template, array $data)
{
ob_start();
include $template;
return ob_get_clean();
}
I think it's echo($_xml);
I'm generating a ton of XML that is to be passed to an API as a post variable when a user click on a form button. I also want to be able to show the user the XML before hand.
The code is sorta like the following in structure:
<?php
$lots of = "php";
?>
<xml>
<morexml>
<?php
while(){
?>
<somegeneratedxml>
<?php } ?>
<lastofthexml>
<?php ?>
<html>
<pre>
The XML for the user to preview
</pre>
<form>
<input id="xml" value="theXMLagain" />
</form>
</html>
My XML is being generated with a few while loops and stuff. It then needs to be shown in the two places (the preview and the form value).
My question is. How do I capture the generated XML in a variable or whatever so I only have to generate it once and then just print it out as apposed to generating it inside the preview and then again inside the form value?
<?php ob_start(); ?>
<xml/>
<?php $xml = ob_get_clean(); ?>
<input value="<?php echo $xml ?>" />͏͏͏͏͏͏
Put this at your start:
ob_start();
And to get the buffer back:
$value = ob_get_contents();
ob_end_clean();
See http://us2.php.net/manual/en/ref.outcontrol.php and the individual functions for more information.
It sounds like you want PHP Output Buffering
ob_start();
// make your XML file
$out1 = ob_get_contents();
//$out1 now contains your XML
Note that output buffering stops the output from being sent, until you "flush" it. See the Documentation for more info.
When using frequently, a little helper could be helpful:
class Helper
{
/**
* Capture output of a function with arguments and return it as a string.
*/
public static function captureOutput(callable $callback, ...$args): string
{
ob_start();
$callback(...$args);
$output = ob_get_contents();
ob_end_clean();
return $output;
}
}
You could try this:
<?php
$string = <<<XMLDoc
<?xml version='1.0'?>
<doc>
<title>XML Document</title>
<lotsofxml/>
<fruits>
XMLDoc;
$fruits = array('apple', 'banana', 'orange');
foreach($fruits as $fruit) {
$string .= "\n <fruit>".$fruit."</fruit>";
}
$string .= "\n </fruits>
</doc>";
?>
<html>
<!-- Show XML as HTML with entities; saves having to view source -->
<pre><?=str_replace("<", "<", str_replace(">", ">", $string))?></pre>
<textarea rows="8" cols="50"><?=$string?></textarea>
</html>