php - How to get all nodes with xpath and return as resposeXML to js?
Get the solution ↓↓↓How to retrieve xml using xpath and send back to client js as responseXML?
I have php as the server, js as the client, need the specified data and display as html table.
here's my xml
// goods.xml
<items>
<item>
<id>1</id>
<itemname>Apple iPhone X</itemname>
<itemqty>20</itemqty>
</item>
<item>
<id>2</id>
<itemname>Apple iPhone 7</itemname>
<itemqty>20</itemqty>
</item>
<item>
<id>3</id>
<itemname>Apple iPhone 8</itemname>
<itemqty>2</itemqty>
</item>
</items>
I want those item with over 10 quantities, I was only able to get only one of them with my php file
// handle.php
$xmlFile = "../../data/goods.xml";
$doc->load($xmlFile);
$xpath = new DOMXPath($doc);
$xml = new SimpleXMLElement($xmlFile, NULL, TRUE);
$nodes = $xml->xpath("/items/item[itemqty>10]");
echo $doc->saveXML($xpathresultset->item(0)); // send the xml response back to the client
Then I only got the first result, I couldn't get both result (id 1 & id 2)
<item>
<id>1</id>
<itemname>Apple iPhone X</itemname>
<itemqty>20</itemqty>
</item>
But I want
<item>
<id>1</id>
<itemname>Apple iPhone X</itemname>
<itemqty>20</itemqty>
</item>
<item>
<id>2</id>
<itemname>Apple iPhone 7</itemname>
<itemqty>20</itemqty>
</item>
Any help would be appreciated!!
Answer
Solution:
This is probably more easily done usingDOMDocument
thanSimpleXML
, as you can then usexpath
to search for nodes withitemqty <= 10
and remove them from the document:
$xml = '<items>
<item>
<id>1</id>
<itemname>Apple iPhone X</itemname>
<itemqty>20</itemqty>
</item>
<item>
<id>2</id>
<itemname>Apple iPhone 7</itemname>
<itemqty>20</itemqty>
</item>
<item>
<id>3</id>
<itemname>Apple iPhone 8</itemname>
<itemqty>2</itemqty>
</item>
</items>';
$doc = new DOMDocument();
$doc->loadXML($xml);
$xpath = new DOMXPath($doc);
foreach ($xpath->query('/items/item[itemqty<=10]') as $node) {
$node->parentNode->removeChild($node);
}
echo $doc->C14N();
Output:
<items>
<item>
<id>1</id>
<itemname>Apple iPhone X</itemname>
<itemqty>20</itemqty>
</item>
<item>
<id>2</id>
<itemname>Apple iPhone 7</itemname>
<itemqty>20</itemqty>
</item>
</items>
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: your system folder path does not appear to be set correctly. please open the following file and correct this: index.php
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.