XML String into PHP - php

I feel like I'm going crazy. I need to take a string of text from an xml file, and define it as a PHP variable and output it into an HTML page. I can't figure out why this wont work. Any ideas??
I have this xml document (people.xml):
<?xml version="1.0"?>
<datas>
<person>
<people>
<owner>Joe Blow</owner>
</people>
</person>
</datas>
This PHP (db.php):
<?php
$xml = simplexml_load_file('people.xml')
or die("Error: Can't load people");
$xml->person->people->owner = $owner;
?>
This HTML(index.php):
<?php include 'db.php';?>
<label for="owner-1"><?php echo $owner ?></label>

Assuming everything else is right / Based on the code you have shown,
$xml->person->people->owner = $owner;
should be
$owner = $xml->person->people->owner;
You are trying to assign the value of $owner to $xml->person->people->owner
It should be the other way round.

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

retrieving an xml file from mysql and using it in as a variable with php

I'm retrieving an XML code from the database and storing it as a variable in php. However when I try to use this variable inside an XML code, it gives me an error. Here is my code:
<?php
$conn = mysqli_connect('localhost', 'root', '', 'thisdatabase');
$result = mysqli_query($conn, 'SELECT * FROM createdproduct');
while ($row = mysqli_fetch_assoc($result))
{
//$selected = (isset($_POST['list']) && $_POST['list'] == $row['id']) ? 'selected' : '';
//echo htmlentities($row["productURL"]);
$test = htmlspecialchars($row["productURL"]);
}
//echo htmlentities($test);
?>
and this is my XML wrapped in php:
<?php
//some code
$xml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<order xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://api.mydomain.net">
<orderItems>
'.$test.'
</orderItems>
<payment>
<type>typ</type>
</payment>
<shipping>
<shippingType id="00"/>
<address type="private">
<person> <
<salution id="1"/>
<firstName>person</firstName>
<lastName>person</lastName>
</person>
<street>street</street>
<houseNumber>00</houseNumber>
<city>city</city>
<country code="US">USA</country>
<state code="mm">California</state>
<zipCode>111</zipCode>
<email>aaa#mydomain.net</email>
<phone>+49 341 789 123</phone>
<fax>+49 341 789 123</fax>
</address>
</shipping>
</order>';
//some code
?>
Your error code is rather generic but I suspect the issue is in the data you're pulling from the database and using in the $test variable.
As discussed above, you might try confirming this by using a simple word in place of the actual data, like: $test = 'something';. The reason I believe this to be the problem is because htmlentities() is intended for use in HTML, not XML.
You might consider trying htmlspecialchars() instead.
EDIT: I knew I had read this on SO somewhere, check this post out for further detailed information.
I was able to get the result I wanted using html_entity_decode. Thank you

Xml PHP Get attributes and its children value

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.

xml and php getting tag elements with certain element and outputting

I am have two xml files.. I first get one and loop through it then I need to take an id from the first xml file and find it in the second one and echo out the results associated with that id. If I were to do this with SQL I would simply do this:
$query = (SELECT * FROM HotelSummary WHERE roomTypeCode = '$id') or die();
while($row=mysql_fetch_array($query)){
$name = $row['Name'];
}
echo $name;
How can I do this is in xml and php??
I recommend you to read the DOMDocument documentation.
It's quite heavy but also powerful (not always clear what happens, but the Internet shold always give you a solution)
You can simply walk through your first document, finding your Id and then find your DOMElement via an XPath.
<?php
$dom = new DOMDocument();
$dom->load('1.xml');
foreach ($dom->getElementsByTagName('article') as $node) {
// your conditions to find out the id
$id = $node->getAttribute('id');
}
$dom = new DOMDocument();
$dom->load('2.xml');
$xpath = new DOMXPath($dom);
$element = $xpath->query("//*[#id='".$id."']")->item(0);
// would echo "top_2" based on my example files
echo $element->getAttribute('name');
Based on following test files:
1.xml
<?xml version="1.0" encoding="UTF-8"?>
<articles>
<article id="foo_1">
<title>abc</title>
</article>
<article id="foo_2">
<title>def</title>
</article>
</articles>
2.xml
<?xml version="1.0" encoding="UTF-8"?>
<tests>
<test id="foo_1" name="top_1">
</test>
<test id="foo_2" name="top_2">
</test>
</tests>
Use SimpleXML to create an object representation of the file. You can then loop through the elements of the Simple XML object.
Depending on the format of the XML file:
Assuming it is:
<xml>
<roomTypeCode>
<stuff>stuff</stuff>
<name>Skunkman</name>
</roomTypeCode>
<roomTypeCode>
<stuff>other stuff</stuff>
<name>Someone Else</name>
</roomTypeCode>
</xml>
It would be something like this:
$xml = simplexml_load_file('xmlfile.xml');
for($i = 0; $i < count($xml->roomTypeCode); $i++)
{
if($xml->roomTypeCode[$i]->stuff == "stuff")
{
$name = $xml->roomTypeCode[$i]->name;
}
}
That connects to the XML file, finds how many roomTypeCode entries there are, searches for the value of "stuff" within and when it matches it correctly, you can access anything having to do with that XML entry.

Pulling a specific field with php out of a xml upload

I've been trying to get the id field to pull and have no idea where I'm going wrong. The rest of the data pulls correctly but I'm trying to add something new to some existing code and everything I've tried hasn't worked. Below is my XML and the PHP code I've been working off of.
I haven't worked with a combo of xml and php before so I could really use a push in the right direction.
<?xml version="1.0" encoding="UTF-8"?>
<enterprise>
<person>
<sourcedid>
<source>Spirit Awards</source>
<id>SP8675309</id>
</sourcedid>
<userid>...</userid>
<name>
<fn>...</fn>
</name>
<email>...</email>
</person>
PHP code:
function get_userid(){
return $this->uid;
}
function __construct($xmlData){
$this->uid = (string)$xmlData->id;
}
SimpleXMLdocs makes this ... well ... simple. The XML you've posted is missing a closing </enterprise> tag. Assuming the XML you're actually parsing includes the closing tag, consider:
$str = '<?xml version="1.0" encoding="UTF-8"?>
<enterprise>
<person>
<sourcedid>
<source>Spirit Awards</source>
<id>SP8675309</id>
</sourcedid>
<userid>...</userid>
<name>
<fn>...</fn>
</name>
<email>...</email>
</person>
</enterprise>
';
$xml = simplexml_load_string($str);
$var = (string) $xml->person->sourcedid->id;
echo $var; // outputs: SP8675309

Categories