Frage

I got a HTML table that looks like this:

<table id="xp">               
        <tbody >
            <tr>
                <td>
                <input type="text" data-type="string" value="testvalue" class="text">
                </td>
                <td>
                <input type="text" data-type="string" value="" class="text">
                </td>
            </tr>

        </tbody>  
</table>

Now I want to use phpQuery to change the value of the input like so:

require('**********/phpQuery.php');
$newsURL = "http://***********/index.php";
$newspage = file_get_contents($newsURL);

    if( $newspage )
    {           
      $pq = phpQuery::newDocument($newspage); 
                 foreach(pq('.text') as $stuffs)
                 {
                  $stuffs->val('ompalompa');
                  $this->assertEquals("ompalompa", $stuffs->val());
         }
             }

Am am using phpUnit assert to see the result but I just get this error:

//Call to undefined method DOMElement::val()

When I use the val() method to get the value from the first class element tho like this:

$stuffs = pq('.text')->val();
$this->assertEquals("testvalue", $stuffs);

It works fine and the assertion is passed

Time: 8 seconds, Memory: 3.25Mb
OK (1 test, 1 assertion)

As i understand from the phpQuery manual val() without a parameter is just fetching the value fo the first element with the choosen selector and val() with a value sets the value of every element with the choosen selector as shown below. Can anyone explain to me wht the problem is if I am missunderstanding the documentation or if something else in my code is broken.

  • val() Get the content of the value attribute of the first matched element.
  • val($val) Set the value attribute of every matched element.
War es hilfreich?

Lösung

In the docs for phpQuery, it states that when you loop with foreach a php DOM is returned. This must be passed back to phpQuery useing pq().

Change all occurances of $stuffs to pq($stuffs)

Out of curiosity I did the following as I have never used phpQuery before:

<?
require 'phpQuery-onefile.php';
$html = "<table id=\"xp\">               
        <tbody >
            <tr>
                <td>
                <input type=\"text\" data-type=\"string\" value=\"testvalue\" class=\"text\">
                </td>
                <td>
                <input type=\"text\" data-type=\"string\" value=\"\" class=\"text\">
                </td>
            </tr>

        </tbody>  
</table>";

$pq = phpQuery::newDocument($html); 
foreach(pq('.text') as $stuffs)
{
  pq($stuffs)->val('ompalompa');
  echo pq($stuffs)->val()."</br>";
}

?>

The output was:

ompalompa
ompalompa

If I use:

$stuffs->val('ompalompa');

Then

Fatal error: Call to undefined method DOMElement::val() in /var/www/index.php on line 20
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top