I had some trouble wording the question, but I think I can explain it better once I show the code:
This is my xml file (test.xml)
<?xml version="1.0" encoding="utf-8"?>
<root>
<entry id="1">
<post>05/12/2014 12:00:00</post>
<page>1</page>
<part>1</part>
<body>BODY TEXT 1</body>
</entry>
<entry id="2">
<post>05/14/2014 12:00:00</post>
<part>1</part>
<page>2</page>
<body>BODY TEXT 2</body>
</entry>
</root>
This is my PHP code (call.php)
<?php
if(isset($_GET['p']))
{
$p=$_GET['p'];
echo $p . "<br>";
$xml=simplexml_load_file("test.xml");
$day=$xml->entry[$p]->post;//<-----------PROBLEM AREA
$post=strtotime("$day");
echo $post . "<br>";
echo time() . "<br>";
if(time() >= $post)
{
echo $xml->entry[$_GET['p']]->page . "<br>";
echo $xml->entry[$_GET['p']]->part . "<br>";
}
}else{
echo "<p>Main Page Stuff</p>";
}
?>
The problem I am having is with the $day variable. If I replace [$p] with [1] or [0], it runs perfectly, but I need to have it called with a variable so I can change what part of the XML file is loaded depending on the query string, currently '?p=1'.
The echo $p results prints out 1 or 0 depending on what I put into the URL, so the $_GET is working properly, but if I put either $p or $_GET into entry[] it gives the error
Notice: Trying to get property of non-object in C:\wamp\www\xmltest\call.php on line 20
(line 20 is the one marked 'PROBLEM AREA')
is there any way to fix this problem so I can call either the first or the second depending on the query string?
I could not find a way to make the solution I was hoping for work, so I worked around it by making a new xml file for each entry instead of having each entry in one xml file.
Code used to load the xml file:
p="docs/".$_GET['p'].".xml";
if(file_exists($p))
{
$xml=simplexml_load_file($p);
$day=$xml->entry->post;
$value = $xml->entry->body;
echo "Part ".$xml->entry->part;
echo "Page ".$xml->entry->page;
}
Related
I am working with PHP and SimpleXML/XPath, and I'm just wondering how to set a certain parent (with a certain attribute value) equal to a variable, which I could use in a 'foreach'?
I'm currently getting this error:
Notice: Array to string conversion
and this output
Array
Thanks for any leads.
Here is the php code:
<?php
$url = "test_b.xml";
$xml = simplexml_load_file($url);
$xml_report_abbrev_b = $xml->xpath('//poster[#name="U-Verify"]')[0];
if($xml_report_abbrev_b){
foreach($xml_report_abbrev_b as $node_a) {
echo '<h1>'.$node_a->xpath('/full_image/#url').'</h1>';
}
} else {
echo 'XPath query failed';
}
?>
Here's the xml:
<data>
<poster name="U-Verify" id="uverify">
<full_image url="u-verify.jpg"/>
<full_other url=""/>
</poster>
<poster name="Minimum" id="min">
<full_image url="min.jpg"/>
<full_other url="spa_min.jpg"/>
</poster>
</data>
Using SimpleXML's element access and attribute access directly instead of using the XPath query will make the code simpler and perform better.
Your code could be reduced to...
$xml_report_abbrev_b = $xml->xpath('//poster[#name="U-Verify"]');
if($xml_report_abbrev_b){
echo '<h1>'.$xml_report_abbrev_b[0]->full_image['url'].'</h1>';
} else {
echo 'XPath query failed';
}
Note the way the echo line says - with the <poster> element you found from the XPath expression, use the <full_image> element and fetch the url attribute.
I also moved the [0] into the if because if the XPath didn't find a value, this produced an error as there isn't any data to get a value from.
This outputs...
<h1>u-verify.jpg</h1>
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
XML:
<?xml version="1.0" encoding="ISO-8859-1"?>
<lessons>
<lesson level="1" course="2">
<name type="Dog" category="Animals">Dog name</name>
</lesson>
</lessons>
I want to get the values saved like this:
$type = "Dog";
$category = "Animals";
$name = "dog name";
This is what I've done:
foreach($xml->name as $name){
$type = $name['type'];
$category = $name['category'];
echo "Type: $type Category: $category<br>";
// AND TO get the text, haven't figuered it out yet.. <name ..="" ..="">text</name>
}
But it doesn't work. Don't get any errors neither any output. Any ideas?
EDIT:
OK. I changed foreach($xml->name as $name)
to foreach($xml->lesson->name as $name)
so I get the values of the attribute. But now I don't know how to get the value of the children.
I've tried this: $xml->lesson->children()
It prints children()
SOLVED: $text = $xml->lesson->children();
echo $text;
PROBLEM WAS: I'm using utf-8 in my other code but didn't change it.
Edit : this part related to a question typo. If you copied your xml directly from where you were editting it, then part of the problem might be that it is malformed. You have an opening <lessons> but you appear to wrongly try to close it with </lesson>.
Also, depending on your root node settings, ->name may or may not be a child of the $xml object. Can you post a var_dump() of it and get some clues?
I think, there is some problem in your xml.
-> You have to close lessons tag correctly.Because you have entered </lesson> (see last line) instead of </lessons>. If you start any tag, you should use the same tag name while closing..
you can use this code to extract values from your xml,
<?php
$xmlstring='<lessons>
<lesson level="1" course="2">
<name type="Dog" category="Animals">Dog name</name>
</lesson>
</lessons>';
$xml = simplexml_load_string($xmlstring);
$ATTRIBUTE=array();
$counter = 0;
foreach($xml->children() as $key=>$child)
{
$counter++;
$ATTRIBUTE[$counter]["type"]=$child->name->attributes()->type;
$ATTRIBUTE[$counter]["category"]=$child->name->attributes()->category;
$ATTRIBUTE[$counter]["value"]= $child->name;
}
echo "<pre>";
print_r($ATTRIBUTE);
?>
here you will get everything in array. So you can fetch based on your requirement.
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.
I've successfully integrated the LinkedIn API with my website, but I'm struggling to extract information from the XML. At the moment I'm just trying to print it out so I can proceed to use the user's information once they have logged in and given permission.
Below is the format of the XML, and further down is the code I am using to extract the information. The "first name", "last name" and "headline" calls work perfectly, but where an element has sub-headings, nothing is printed out. I've tried using
echo 'Positions: ' . $xml->{'positions:(title)'};
but it doesn't work.
Here is the XML:
<person>
<id>
<first-name />
<last-name />
<headline>
<location>
<name>
<country>
<code>
</country>
</location>
<industry>
<summary/>
<positions total="">
<position>
<id>
<title>
<summary>
<start-date>
<year>
<month>
</start-date>
<is-current>
<company>
<name>
</company>
</position>
</person>
This is the code I've been using to try to extract the information. I know I have to include the sub-heading somehow but I just don't know how!
echo 'First Name: ' . $xml->{'first-name'};
echo '<br/>';
echo 'Last Name: ' . $xml->{'last-name'};
echo '<br/>';
echo 'Headline: ' . $xml->{'headline'};
echo '<br/>';
echo 'Positions: ' . $xml->{'positions'};
Any help would be greatly appreciated, thanks for reading!
Using SimpleXML, you'd access the LinkedIn XML data properties as follows:
Anything with a dash in the property gets {}, so first-name becomes:
$xml->{'first-name'}
Anything without a dash such as headline, is referenced like:
$xml->headline
Anything that is a collection, such as positions, is referenced like:
foreach($xml-positions as $position) {
echo $position->title;
echo $position->{'is-current'};
}
Your XML is not valid, its not well formed. Anyway here's a sample XML and how to use it.
$v = <<<ABC
<vitrine>
<canal>Hotwords</canal>
<product id="0">
<descricao>MP3 Apple iPod Class...</descricao>
<loja>ApetreXo.com</loja>
<preco>à vista R$765,22</preco>
<urlImagem>http://im</urlImagem>
<urlProduto>http://</urlProduto>
</product>
</vitrine>
ABC;
$xml = simplexml_load_string($v);
foreach ($xml->product as $c){
echo $c->loja; //echoing out value of 'loja'
}
Try to use PHP's XML Parser instead:
http://www.php.net/manual/en/function.xml-parse.php
Tried Paul's answer above for:
foreach($xml-positions as $position) {
echo $position->title;
echo $position->{'is-current'};
}
didn't work for me - so I used this - not as elegant but works
for($position_num = 0; $position_num < 10;$position_num++){
echo $xml->positions->position[$position_num]->company->name;
}
Your XML is not well-formed... there are several elements without close tags. So we have no way to know for sure the structure of your XML. (You can't do that in XML like you can in HTML.)
That being said, assuming that <person> is the context node, you can probably get the content of the <title> element using an XPath expression, as in
$xml->xpath('positions/position/title');
I'm assuming $xml is a SimpleXMLElement object.