Parsing xml file with .php extension and php header - php

I have a slight problem. I need to parse a file and populate a web banner with the results. Problem is, the file is called : "_banner_products.php" and it's contents are as follows:
<?php header('Content-Type:text/xml'); ?><?php echo '<?xml version="1.0" encoding="UTF-8"?>'; ?>
<carouselle>
<firstLayer>
<layerName>Leica Disto X310</layerName>
<layerProduct>Disto X310</layerProduct>
<layerPic>http://www.leicaestonia.ee/extensions/boxes_design/flashpics/1334482548.jpg</layerPic>
<layerPrice>0,-</layerPrice>
<layerPriceOld></layerPriceOld>
<layerLink>http://www.leicaestonia.ee/index.php?id=11627</layerLink>
<layerTimer>01.05.2012 00:00</layerTimer>
</firstLayer>
<firstLayer>
.....
.....
</firstLayer>
</carouselle>
How can I loop through this file to group all the "firstLayer" children into one and so on..
If I just use:
$file = fopen("_banner_products.php", "r");
while (!feof($file)){
$line = fgets($file);
}
simplexml_load_file throws this-
"_banner_products.php:1: parser error : Start tag expected, '<' "
Then I only get the contents of the <...> tags meaning there is no way for me to differentiate if I am out of the scope already.
Thanks for anyone responding. If anything is unclear I´ll try to explain more.
EDIT.
Thank you for the solution, indeed using the full URL worked:
simplexml_load_file("http://localhost/MySite/_banner_products.php");

You are having issue because simplexml_load_file is treating your file like a local xml file .. what you need to do is add the full URL
Example
simplexml_load_file("http://localhost/web/_banner_products.php");
Use Case getting layerName for example
_banner_products.php
<?php
header ( 'Content-Type:text/xml' );
echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<carouselle>
<firstLayer>
<layerName>Leica Disto X310</layerName>
<layerProduct>Disto X310</layerProduct>
<layerPic>http://www.leicaestonia.ee/extensions/boxes_design/flashpics/1334482548.jpg</layerPic>
<layerPrice>0,-</layerPrice>
<layerPriceOld></layerPriceOld>
<layerLink>http://www.leicaestonia.ee/index.php?id=11627</layerLink>
<layerTimer>01.05.2012 00:00</layerTimer>
</firstLayer>
<firstLayer>
<layerName>Leica Disto X310</layerName>
<layerProduct>Disto X310</layerProduct>
<layerPic>http://www.leicaestonia.ee/extensions/boxes_design/flashpics/1334482548.jpg</layerPic>
<layerPrice>0,-</layerPrice>
<layerPriceOld></layerPriceOld>
<layerLink>http://www.leicaestonia.ee/index.php?id=11627</layerLink>
<layerTimer>01.05.2012 00:00</layerTimer>
</firstLayer>
</carouselle>
view details
$xml = simplexml_load_file("http://localhost/lab/stockoverflow/_banner_products.php");
echo "<pre>" ;
foreach($xml as $key => $element)
{
echo $element->layerName , PHP_EOL ;
}

The most obvious way to do this is to strip out the first line, and add the XML declaration back in with your code.
You could also parse the file with PHP, using eval(), but be very sure about what you are parsing, as this could be a very large security hole.

Related

Php delete element in xml

I'm trying to use php to delete an xml element but it doesn't work. I tried some different code but no one works. I would also like to use cookies to get element in the future. Can you suggest me what I have to do ? I'm not expert and for this I'm in difficulty.
Here the code:
<?php
$dom = new DOMDocument();
$dom->load("Dati.xml");
$matchingElements = $dom->getElementsByTagName("Matematica");
$totalMatches = $matchingElements->length;
$elementsToDelete = array();
$elementsToDelete[] = $matchingElements->item(0);
foreach ( $elementsToDelete as $elementToDelete ) {
$elementToDelete->parentNode->removeChild($elementToDelete);
}
$dom->save($xmlFileToLoad);
echo "<script type='text/javascript'>";
echo "window.close();";
echo "</script>";
echo "Puoi chiudere questa pagina";
?>
Here the xml:
<?xml version="1.0" encoding="UTF-8"?>
<document>
<Informatica>
<nome>aaaa</nome>
<classe>3C</classe>
<titolo>Informatica</titolo>
<materia>Informatica</materia>
<ISBN>123456789101112</ISBN>
<prezzo>12</prezzo>
<autori>tizio</autori>
<contatto>nanni-lombardo1#hotmail.it</contatto>
<codice>123456</codice>
</Informatica>
<Matematica>
<nome>bbb</nome>
<classe>3C</classe>
<titolo>math</titolo>
<materia>Matematica</materia>
<ISBN>123456789101112</ISBN>
<prezzo>12</prezzo>
<autori>tizio</autori>
<contatto>nanni-lombardo1#hotmail.it</contatto>
<codice>123456</codice>
</Matematica>
</document>
Please be sure to :
Remove the space before your XML start tag
Define your $xmlFileToLoad variable
Make your destination XML writable (see Chmod & permissions)
My test file works fine : https://eu.andredasilva.fr/testandre/test.php (source code : https://eu.andredasilva.fr/testandre/test.php.source)
Base XML : https://eu.andredasilva.fr/testandre/Dati.xml
Result XML : https://eu.andredasilva.fr/testandre/test.xml

php- How to send $_POST data to xml?

I have a php file that contains:
<?php
$no = $_POST['no'];
$url = "http://domain.tld/answer.xml";
?>
The $url stores a URL that links to an xml file and that xml files is like:
<?xml version="1.0" encoding="UTF-8"?>
<vxml version = "2.1" >
<Call> </Call>
</vxml>
I want to pass the $_POST['no'] to my xml file. Suppose if $_POST['no'] is 9999988888, then the tag in xml should be like:
<Call>9999988888</Call>
Can anyone tell how to do this? :)
that xml file is on my own server.
you could use simplexml, as:
$no = $_POST['no'];
$xml = simplexml_load_file('your_xml_file.xml');
$xml->Call = $no;
//save/update your xml
$xml->asXML('your_xml_file.xml');
You need to generate the xml using PHP.
First of all, rename your .xml to .php.
Then, start it using
<?php
header('Content-type: text/xml');
?>
When you reach your call tag, change it to :
<Call><?php echo intval($_GET['no']); ?></Call>
Note: I've assumed your no is a number. If it's not, remove intval. It's nice to have it as it will protect you from injections.
At last, call your XML file using :
$url = "http://domain.tld/answer.php?no=8877454";
Your XML should have some keywords, i.e.
<?xml version="1.0" encoding="UTF-8"?>
<vxml version = "2.1" >
<Call>{{CALL}}</Call>
</vxml>
In your PHP File, just fetch this XML & use str_replace to replace those keywords,
<?php
$no = $_POST['no'];
$url = "http://domain.tld/answer.xml";
$xml = file_get_contents($url);
$newXML = str_replace("{{CALL}}", $no, $xml);
header('Content-type: text/xml');
echo $newXML;
?>

Simple xml returns no values when trying to access nodes

Hi guys very new to the php world.
I am listening for a PHP post that contains xml, when the xml is retrieved i need to access individual nodes. I am able to echo the full xml file but not individual attributes.
Currently I am just sending the data using a chrome extension Postman. There is no front end code. Here is my XML:
<?xml version="1.0" encoding="UTF-8"?>
<job>
<job_ref>abc123</job_ref>
<job_title>Test Engineer</job_title>
</job>
And here is my PHP:
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$xml = file_get_contents('php://input');
echo $xml;
$xml=simplexml_load_file($xml);
echo $xml->job_ref . "<br>";
echo $xml->job_title . "<br>";
}else{
die();
}
Any hep wopuld be amazing am I am very stuck.
Many thanks
simplexml_load_file expect PATH to the XML file, not its content. You have to use simplexml_load_string instead:
$xml = simplexml_load_string($xml);

XML with PHP “echo” getting error “Extra content at the end of the document”

I have asked a question here on how to Generate a sitemap automatically, does it need to be XML?
Here is the solution we have concluded:
<?php
header ("Content-Type:text/xml");
echo '<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
// code to extract and echo links from the file
echo ' </urlset>';
?>
<?PHP
// Original PHP code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
$url = "assets/includes/menu.inc";
$input = #file_get_contents($url) or die("Could not access file: $url");
$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
if(preg_match_all("/$regexp/siU", $input, $matches, PREG_SET_ORDER)) {
foreach($matches as $match) {
// $match[2] = link address
// $match[3] = link text
echo '<url><loc>' . $match[2] . '</loc></url>';
}
}
?>
However, when I tried it shows the error here: http://postimg.org/image/gh5d0k4sx/ - I tried to remove the top line "header ("Content-Type:text/xml");" and it worked, but can I remove that line? the whole thing is for the sake of SEO so I don't know if we can delete the top line, what I am doing wrong?
Anther question: is this file now recognized as an XML file? even that it has .php extension?
Your PHP doesn't get picked up by the browser since it's a server side language.
The header function doesn't modify the body of the page. It's important to keep it in though, or the browser will not recognize the document as XML.
Try removing the closing and opening PHP tags between the two parts of the script. The whitespace inbetween them may be causing your error.
?>
<?PHP
Edit: following the comments, wait until you output your <url> tags before closing urlset
Move the line to the bottom of the PHP:
echo ' </urlset>';
It's also in the best interests of clean XML to understand how to use line breaks and double quotes to achieve a similar effect.
The file will not be picked up by crawlers.
According to the sitemap spec at http://www.sitemaps.org/protocol.html.
The filename must be sitemap.xml.
I would suggest creating the file "sitemap.xml" with
file_put_contents("sitemap.xml", $xmlContent);
A static file is faster and you can cronjob it's re-creation.
How to create a cronjob on linux?
on shell use cronjob -e
your editor opens up
add a new cronjob line, like: 00 22 * * * /path/to/sitemapBuilder.php
this means: execute your sitemap generation script, every day at 22:00
Content of sitemapBuilder.php:
<?php
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
$url = "assets/includes/menu.inc";
$input = #file_get_contents($url) or die("Could not access file: $url");
$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
if(preg_match_all("/$regexp/siU", $input, $matches, PREG_SET_ORDER)) {
foreach($matches as $match) {
// $match[2] = link address
// $match[3] = link text
$xml .= '<url><loc>' . $match[2] . '</loc></url>';
}
}
$xml .= '</urlset>';
file_put_contents('sitemap.xml', $xml);
?>
Write sitemap.xml to the root folder of your web project, e.g. next to index.php.
You might also use a Sitemap Validator to point to your URL and check the file for validity.
For example, http://www.validome.org/google/ might help with that.

Can parse one document, but not another

I have two XML documents, both formatted like this:
<?xml version="1.0" ?>
<article>
<body>
<![CDATA[
*some text*
]]>
</body>
</article>
and I want to echo them using this:
<?php
$xml = simplexml_load_file("." . $filename);
echo $xml->body;
?>
But one of them works, the other just echos nothing. What is going on?
UPDATE:
The document which produces the error contains this appostrophe: '
When this apostrophe is removed, the code works. I need some way of escaping characters like this, how can I do it?
Just echo asXML() you may see your error with the second file.
echo $xml->asXML();
Here is a simple tutorial on SimpleXML: http://php.net/manual/en/simplexml.examples-basic.php
Espace your appostrophe:
<?php
$text = file_get_contents("." . $filename);
$text = str_replace("'", "&apos;", $text);
$xml = simplexml_load_string($text);
echo $xml->body;
?>
Also, someone had a similar problem (no crash but garbage characters) and came up with the same solution. A bit later in that forum thread they speculate on utf8_encode and utf8_decode, which you could also try. Link: http://board.phpbuilder.com/showthread.php?10359181-RESOLVED-SimpleXML-apostrophe-problem&p=10886946&viewfull=1#post10886946

Categories